Java API 开发中使用 OAuth2 鉴权

王林

王林

2023-06-18

1652人浏览

原创

java api 的开发中,鉴权是不可避免的问题。oauth2 是一种流行的鉴权方式,它通过授权访问来保护 api 资源。本文将介绍如何在 java api 开发中使用 oauth2 进行鉴权。

OAuth2 简介

OAuth2 是一种用于授权的开放标准,它允许用户授权第三方应用程序访问他们的服务器资源,而不必分享他们的凭据。OAuth2 标准包括以下角色:

  • Resource Owner:资源拥有者,即用户;
  • Resource Server:资源服务器,提供资源的服务器;
  • Client:客户端,即第三方应用程序;
  • Authorization Server:授权服务器,用于颁发访问令牌。

OAuth2 的授权过程包括以下步骤:

  • Client 向 Authorization Server 发送授权请求;
  • Authorization Server 向 Resource Owner 请求授权;
  • Resource Owner 授权后,Authorization Server 发送访问令牌给 Client;
  • Client 使用访问令牌向 Resource Server 发送请求;
  • Resource Server 验证访问令牌并提供资源。

OAuth2 支持多种授权类型,包括授权码模式、密码模式、客户端模式、隐式授权模式等。在 Java API 开发中,通常使用授权码模式和密码模式。

OAuth2 授权码模式

授权码模式是 OAuth2 中最常用的授权类型,它包含以下步骤:

  • Client 向 Authorization Server 发送授权请求,包括 Client ID 和重定向 URI;
  • Authorization Server 发送登录页面给 Resource Owner,要求 Resource Owner 登录并授权;
  • Resource Owner 授权后,Authorization Server 向重定向 URI 发送授权码;
  • Client 使用授权码向 Authorization Server 发送请求,包括 Client ID 和 Client Secret;
  • Authorization Server 验证 Client ID 和 Client Secret,如果正确,颁发访问令牌给 Client;
  • Client 使用访问令牌向 Resource Server 发送请求。

在 Java API 开发中,可以使用 Spring Security OAuth2 框架实现授权码模式的鉴权。

首先,需要在 pom.xml 文件中添加以下依赖项:

<dependency><groupid>org.springframework.security.oauth</groupid><artifactid>spring-security-oauth2</artifactid><version>2.3.4.RELEASE</version></dependency>

然后,在 Spring MVC 的配置文件中添加以下配置:

<http pattern="/oauth/token" create-session="stateless" authentication-manager-ref="authenticationManager" xmlns="http://www.springframework.org/schema/security"><intercept-url pattern="/oauth/token" access="isAuthenticated()" method="POST"></intercept-url><anonymous enabled="false"></anonymous><http-basic entry-point-ref="clientAuthenticationEntryPoint"></http-basic><custom-filter ref="clientCredentialsTokenEndpointFilter" before="BASIC_AUTH_FILTER"></custom-filter><access-denied-handler ref="oauthAccessDeniedHandler"></access-denied-handler></http><http pattern="/api/**" create-session="never" entry-point-ref="oauthAuthenticationEntryPoint" access-decision-manager-ref="accessDecisionManager" xmlns="http://www.springframework.org/schema/security"><anonymous enabled="false"></anonymous><intercept-url pattern="/api/**" access="ROLE_USER"></intercept-url><custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER"></custom-filter><access-denied-handler ref="oauthAccessDeniedHandler"></access-denied-handler></http><bean id="clientAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint"><property name="realmName" value="spring-boot-oauth2"></property><property name="typeName" value="Basic"></property></bean><bean id="oauthAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint"><property name="realmName" value="spring-boot-oauth2"></property><property name="typeName" value="Bearer"></property></bean><bean id="oauthAccessDeniedHandler" class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler"></bean><bean id="clientCredentialsTokenEndpointFilter" class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter"><property name="authenticationManager" ref="authenticationManager"></property></bean><bean id="resourceServerFilter" class="org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter"><property name="authenticationManager" ref="authenticationManager"></property></bean><bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased" xmlns="http://www.springframework.org/schema/beans"><constructor-arg><list><bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter"></bean><bean class="org.springframework.security.access.vote.RoleVoter"></bean><bean class="org.springframework.security.access.vote.AuthenticatedVoter"></bean></list></constructor-arg></bean><authentication-manager id="authenticationManager"><authentication-provider user-service-ref="userDetailsService"></authentication-provider></authentication-manager><bean id="userDetailsService" class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl"><property name="dataSource" ref="dataSource"></property></bean>

其中,/oauth/token 是用于获取访问令牌的路径,/api/** 是需要进行鉴权的路径。

使用 OAuth2RestTemplate 发送请求时,需要先获取访问令牌,代码如下:

Java JDK 25
Java JDK 25

Java JDK 25 来自 OpenJDK 官方归档,版本为 JDK 25,本条下载地址已指向官方 Windows x64 zip 安装包直链,适合调试旧项目或兼容旧版 Java 运行环境。

下载
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(client, context);
AuthorizationCodeResourceDetails details = (AuthorizationCodeResourceDetails)client.getResource();
AuthorizationCodeAccessTokenProvider provider = new AuthorizationCodeAccessTokenProvider();
Authentication auth = new UsernamePasswordAuthenticationToken(username, password);
AccessTokenRequest tokenRequest = provider.createAccessTokenRequest(details, auth);
OAuth2AccessToken accessToken = provider.obtainAccessToken(details, tokenRequest);
restTemplate.getOAuth2ClientContext().setAccessToken(accessToken);

其中,client 是 OAuth2ProtectedResourceDetails 类型的对象,包含 Client ID 和 Client Secret 等信息。

OAuth2 密码模式

密码模式是 OAuth2 中适用于信任客户端的授权类型,它包含以下步骤:

  • Client 向 Authorization Server 发送请求,包括 Client ID、Client Secret 和 Resource Owner 的用户名密码;
  • Authorization Server 验证 Client ID、Client Secret 和用户名密码,如果正确,颁发访问令牌给 Client;
  • Client 使用访问令牌向 Resource Server 发送请求。

在 Java API 开发中,可以使用 Spring Security OAuth2 框架实现密码模式的鉴权。

首先,需要在 pom.xml 文件中添加以下依赖项:

<dependency><groupid>org.springframework.security.oauth</groupid><artifactid>spring-security-oauth2</artifactid><version>2.3.4.RELEASE</version></dependency>

然后,在 Spring MVC 的配置文件中添加以下配置:

<http pattern="/oauth/token" create-session="stateless" authentication-manager-ref="authenticationManager" xmlns="http://www.springframework.org/schema/security"><intercept-url pattern="/oauth/token" access="isAuthenticated()" method="POST"></intercept-url><anonymous enabled="false"></anonymous><http-basic entry-point-ref="clientAuthenticationEntryPoint"></http-basic><custom-filter ref="clientCredentialsTokenEndpointFilter" before="BASIC_AUTH_FILTER"></custom-filter><access-denied-handler ref="oauthAccessDeniedHandler"></access-denied-handler></http><http pattern="/api/**" create-session="never" entry-point-ref="oauthAuthenticationEntryPoint" access-decision-manager-ref="accessDecisionManager" xmlns="http://www.springframework.org/schema/security"><anonymous enabled="false"></anonymous><intercept-url pattern="/api/**" access="ROLE_USER"></intercept-url><custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER"></custom-filter><access-denied-handler ref="oauthAccessDeniedHandler"></access-denied-handler></http><bean id="clientAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint"><property name="realmName" value="spring-boot-oauth2"></property><property name="typeName" value="Basic"></property></bean><bean id="oauthAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint"><property name="realmName" value="spring-boot-oauth2"></property><property name="typeName" value="Bearer"></property></bean><bean id="oauthAccessDeniedHandler" class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler"></bean><bean id="clientCredentialsTokenEndpointFilter" class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter"><property name="authenticationManager" ref="authenticationManager"></property></bean><bean id="resourceServerFilter" class="org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter"><property name="authenticationManager" ref="authenticationManager"></property></bean><bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased" xmlns="http://www.springframework.org/schema/beans"><constructor-arg><list><bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter"></bean><bean class="org.springframework.security.access.vote.RoleVoter"></bean><bean class="org.springframework.security.access.vote.AuthenticatedVoter"></bean></list></constructor-arg></bean><authentication-manager id="authenticationManager"><authentication-provider user-service-ref="userDetailsService"></authentication-provider></authentication-manager><bean id="userDetailsService" class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl"><property name="dataSource" ref="dataSource"></property></bean>

其中,/oauth/token 是用于获取访问令牌的路径,/api/** 是需要进行鉴权的路径。

使用 OAuth2RestTemplate 发送请求时,需要先获取访问令牌,代码如下:

OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(details, new DefaultOAuth2ClientContext());
restTemplate.getOAuth2ClientContext().setAccessToken(accesstoken);

其中,details 是 ResourceOwnerPasswordResourceDetails 类型的对象,包含 Client ID、Client Secret、用户名和密码等信息。

总结

在 Java API 开发中使用 OAuth2 进行鉴权可以保护 API 资源的安全,并且可以让用户更加方便地授权第三方应用程序访问他们的服务器资源。本文介绍了 OAuth2 的授权码模式和密码模式,并且提供了使用 Spring Security OAuth2 框架实现鉴权的示例代码。希望可以对 Java API 开发者有所帮助。

大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!

相关专题

更多
火山引擎API Key获取教程
火山引擎API Key获取教程

火山引擎API Key适合需要调用火山引擎云服务、AI模型、火山方舟接口或其他开放能力的开发者参考。本专题整理控制台入口、账号认证、服务开通、API Key创建、密钥复制保存、权限检查、调用测试和Key无效等常见问题排查。

2026.08.04

1

10

火山引擎API接入教程
火山引擎API接入教程

火山引擎API接入适合需要在应用、脚本、后台服务或AI工具中调用火山引擎能力的开发者参考。本专题整理控制台入口、服务开通、API Key获取、接口地址配置、请求参数填写、调用测试、权限设置、额度查询和常见接口报错排查。

2026.08.04

3

10

火山引擎DeepSeek API调用教程
火山引擎DeepSeek API调用教程

火山引擎DeepSeek API适合需要在应用、脚本、智能体或AI编程工具中调用DeepSeek模型的开发者参考。本专题整理火山引擎控制台入口、模型服务开通、API Key获取、Base URL配置、模型名称填写、调用测试、额度查询和常见接口报错排查。

2026.08.04

2

10

火山引擎控制台操作教程
火山引擎控制台操作教程

火山引擎控制台中常用功能包括API密钥管理、模型调用配置、云资源查看、账单明细、用量统计和权限分配。本专题整理控制台基础操作、服务开通流程、Key创建与保存、费用消耗查看、子账号权限设置和调用失败排查,方便开发者完成日常管理。

2026.08.04

3

10

PDF与PPT格式转换操作方法及在线转换技巧
PDF与PPT格式转换操作方法及在线转换技巧

本专题聚焦 PDF 与 PPT 文件格式转换需求,整理 PDF 转 PPT 在线转换方法、PPT 批量转换 PDF 操作步骤、转换后格式错乱处理以及文档版式检查技巧。通过详细教程帮助用户掌握 PDF、PPT 双向转换方法,解决演示文稿制作、文件整理和办公格式转换中的常见问题,提高办公效率。

2026.07.31

112

6

PDF合并文件操作方法与在线批量合并技巧
PDF合并文件操作方法与在线批量合并技巧

本专题聚焦 PDF 文件合并与文档整理需求,整理多个 PDF 合并成一个文件、图片批量转换 PDF、合同附件合并发送以及在线 PDF 合并操作方法等实用教程。通过详细步骤介绍 PDF 合并流程、文件顺序检查技巧和免费在线合并方案,帮助用户快速整理零散文档,提高办公文件处理效率。

2026.07.31

88

8

PDF转Word在线转换与文档编辑处理方法
PDF转Word在线转换与文档编辑处理方法

本专题聚焦 PDF 转 Word 文件转换与办公文档处理需求,整理 PDF 在线转换成 Word、PDF 转可编辑 Word、PDF 文件格式转换操作步骤以及转换后版式错乱、图片无法编辑等常见问题解决方法。通过详细教程帮助用户快速掌握 PDF 转 Word 技巧,提高办公文件处理效率。

2026.07.31

87

5

CodeIgniter下载教程
CodeIgniter下载教程

本合集由PHP中文网精心整理,为您提供CodeIgniter下载教程与官方正版下载安装指南。内容涵盖CI3/CI4官方获取渠道、Composer依赖安装及环境配置全流程。助您安全、高效地搭建轻量级PHP框架,轻松开启Web应用开发之旅。

2026.07.30

116

10

CodeIgniter数据库配置指南
CodeIgniter数据库配置指南

PHP中文网为您提供CodeIgniter数据库配置指南合集。本专题全面解析CI框架数据配置方法,涵盖配置文件修改、多环境连接、动态切换数据库及常见连接错误排查等实战技巧。内容详实易懂,助您轻松掌握CodeIgniter数据库配置,快速解决开发难题,提升项目构建效率。

2026.07.30

45

15

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Java JDBC数据库连接官方教程
Java JDBC数据库连接官方教程

共0课时 | 0人学习

Java 26官方文档
Java 26官方文档

共0课时 | 0人学习