先说步骤:
在 spring security 中整合 oauth2 与 jwt,可实现基于令牌的认证授权机制,适合分布式系统场景。以下是详细的整合步骤和核心配置:
1. 依赖引入
在pom.xml中添加核心依赖(以 spring boot 为例):
<!-- spring security oauth2 -->
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-security</artifactid>
</dependency>
<dependency>
<groupid>org.springframework.security.oauth</groupid>
<artifactid>spring-security-oauth2</artifactid>
<version>2.3.8.release</version>
</dependency>
<!-- jwt支持 -->
<dependency>
<groupid>io.jsonwebtoken</groupid>
<artifactid>jjwt</artifactid>
<version>0.9.1</version>
</dependency>
<!-- spring web(用于测试接口) -->
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-web</artifactid>
</dependency>
2. 核心配置
2.1 jwt 工具类
用于生成、解析 jwt 令牌:
@component
public class jwttokenutil {
// 密钥(实际项目中需加密存储)
private static final string secret = "your-secret-key";
// 过期时间(7天)
private static final long expiration = 604800000l;
// 生成jwt令牌
public string generatetoken(string username) {
date now = new date();
date expirationdate = new date(now.gettime() + expiration);
return jwts.builder()
.setsubject(username)
.setissuedat(now)
.setexpiration(expirationdate)
.signwith(signaturealgorithm.hs512, secret)
.compact();
}
// 从令牌中获取用户名
public string getusernamefromtoken(string token) {
return jwts.parser()
.setsigningkey(secret)
.parseclaimsjws(token)
.getbody()
.getsubject();
}
// 验证令牌有效性
public boolean validatetoken(string token) {
try {
jwts.parser().setsigningkey(secret).parseclaimsjws(token);
return true;
} catch (exception e) {
return false;
}
}
}
2.2 oauth2 配置(授权服务器)
配置授权服务器,指定 jwt 作为令牌格式:
@configuration
@enableauthorizationserver
public class authorizationserverconfig extends authorizationserverconfigureradapter {
@autowired
private authenticationmanager authenticationmanager;
@autowired
private userdetailsservice userdetailsservice;
@autowired
private jwttokenutil jwttokenutil;
// 配置客户端信息(如客户端id、密钥、授权类型等)
@override
public void configure(clientdetailsserviceconfigurer clients) throws exception {
clients.inmemory()
.withclient("client-id") // 客户端id
.secret(passwordencoder().encode("client-secret")) // 客户端密钥
.authorizedgranttypes("password", "refresh_token") // 支持的授权类型
.scopes("read", "write") // 权限范围
.accesstokenvalidityseconds(3600) // 访问令牌过期时间
.refreshtokenvalidityseconds(86400); // 刷新令牌过期时间
}
// 配置令牌存储(使用jwt)
@bean
public jwtaccesstokenconverter accesstokenconverter() {
jwtaccesstokenconverter converter = new jwtaccesstokenconverter() {
@override
protected string encode(oauth2accesstoken accesstoken, oauth2authentication authentication) {
// 自定义jwt载荷(可选)
map<string, object> claims = new hashmap<>(accesstoken.getadditionalinformation());
claims.put("username", authentication.getname());
claims.put("authorities", authentication.getauthorities().stream()
.map(grantedauthority::getauthority)
.collect(collectors.tolist()));
defaultoauth2accesstoken customtoken = new defaultoauth2accesstoken(accesstoken);
customtoken.setadditionalinformation(claims);
return super.encode(customtoken, authentication);
}
};
converter.setsigningkey(jwttokenutil.secret); // 设置签名密钥
return converter;
}
// 配置令牌服务
@bean
public authorizationservertokenservices tokenservices() {
defaulttokenservices services = new defaulttokenservices();
services.setclientdetailsservice(clientdetailsservice());
services.setsupportrefreshtoken(true);
services.settokenstore(tokenstore());
services.setaccesstokenvalidityseconds(3600);
services.setrefreshtokenvalidityseconds(86400);
return services;
}
// jwt令牌存储
@bean
public tokenstore tokenstore() {
return new jwttokenstore(accesstokenconverter());
}
@override
public void configure(authorizationserverendpointsconfigurer endpoints) {
endpoints
.authenticationmanager(authenticationmanager)
.userdetailsservice(userdetailsservice)
.tokenstore(tokenstore())
.accesstokenconverter(accesstokenconverter());
}
@bean
public passwordencoder passwordencoder() {
return new bcryptpasswordencoder();
}
}
2.3 资源服务器配置
配置受保护的资源,验证 jwt 令牌:
@configuration
@enableresourceserver
public class resourceserverconfig extends resourceserverconfigureradapter {
@autowired
private jwttokenutil jwttokenutil;
// 资源id(需与授权服务器配置一致)
private static final string resource_id = "resource-id";
@override
public void configure(resourceserversecurityconfigurer resources) {
resources
.resourceid(resource_id)
.tokenstore(tokenstore()); // 使用jwt令牌存储
}
// 配置资源访问规则
@override
public void configure(httpsecurity http) throws exception {
http
.authorizerequests()
.antmatchers("/public/**").permitall() // 公开接口
.antmatchers("/api/**").authenticated() // 需认证的接口
.antmatchers("/admin/**").hasrole("admin"); // 需admin角色
}
@bean
public tokenstore tokenstore() {
// 配置jwt验证
return new jwttokenstore(new jwtaccesstokenconverter() {{
setsigningkey(jwttokenutil.secret);
}});
}
}
2.4 spring security 配置
配置用户认证信息和密码加密:
@configuration
@enablewebsecurity
public class securityconfig extends websecurityconfigureradapter {
@bean
@override
public authenticationmanager authenticationmanagerbean() throws exception {
return super.authenticationmanagerbean();
}
@bean
@override
public userdetailsservice userdetailsservice() {
// 内存用户(实际项目中替换为数据库查询)
userdetails user = user.withusername("user")
.password(passwordencoder().encode("123456"))
.roles("user")
.build();
userdetails admin = user.withusername("admin")
.password(passwordencoder().encode("123456"))
.roles("admin")
.build();
return new inmemoryuserdetailsmanager(user, admin);
}
@bean
public passwordencoder passwordencoder() {
return new bcryptpasswordencoder();
}
}
3. 测试接口
编写测试接口验证效果:
@restcontroller
public class testcontroller {
// 公开接口
@getmapping("/public/hello")
public string publichello() {
return "public hello!";
}
// 需认证的接口
@getmapping("/api/hello")
public string apihello(authentication authentication) {
return "api hello, " + authentication.getname() + "!";
}
// 需admin角色的接口
@getmapping("/admin/hello")
public string adminhello(authentication authentication) {
return "admin hello, " + authentication.getname() + "!";
}
}
4. 测试流程
4.1 获取令牌
通过password模式请求授权服务器的令牌端点:
post http://localhost:8080/oauth/token content-type: application/x-www-form-urlencoded authorization: basic y2xpzw50lwlkomnsawvudc1zzwnyzxq= # client-id:client-secret的base64编码 grant_type=password&username=user&password=123456
返回结果(jwt 格式的 access_token):
{
"access_token": "eyjhbgcioijiuzuxmij9...",
"token_type": "bearer",
"refresh_token": "eyjhbgcioijiuzuxmij9...",
"expires_in": 3599,
"scope": "read write"
}4.2 访问受保护资源
使用获取的access_token访问接口:
get http://localhost:8080/api/hello authorization: bearer eyjhbgcioijiuzuxmij9...
返回:
api hello, user!
关键注意事项
- 密钥安全:jwt 签名密钥需妥善保管,避免硬编码(可通过配置中心或环境变量注入)。
- 令牌过期:合理设置
access_token和refresh_token的过期时间,平衡安全性和用户体验。 - 自定义载荷:可在 jwt 中添加用户角色、权限等信息,减少资源服务器查询数据库的次数。
- https:生产环境必须使用 https 传输令牌,防止中间人攻击。
通过以上配置,即可实现 spring security oauth2 与 jwt 的整合,支持基于令牌的认证授权。
在来讲几个简单的概念:
jwt 令牌包含了用户信息(或其他数据),并通过数字签名来保证这些信息的完整性和真实性。
具体来说,jwt 令牌由三部分组成(用 . 分隔):
- 头部(header):说明签名算法(比如 hmac、rsa 等)。
- 载荷(payload):存放实际要传递的信息(比如用户 id、角色、过期时间等,这些就是 “用户信息”)。
- 签名(signature):用头部指定的算法,结合服务器的密钥(或私钥),对 “头部 + 载荷” 进行加密生成的数字签名。
所以,jwt 不只是数字签名,而是 “信息 + 签名” 的组合体。签名的作用是:
- 证明载荷里的信息没被篡改(因为篡改后签名会失效);
- 证明信息确实来自可信的服务器(因为只有服务器有密钥能生成正确的签名)。
简单讲,jwt 就像一封 “带防伪签名的信”:信里写了内容(用户信息),信封上的签名(数字签名)保证信没被拆过、没被改,且确实是发件人(服务器)发的。
jwt可以使用hmac算法或使用rsa的公钥/私钥对来签名,防止被篡改。 官网:https://jwt.io/
jwt 令牌的优点:
jwt 基于json,非常方便解析。
可以在令牌中自定义丰富的内容,易扩展。
通过非对称加密算法及数字签名技术,jwt防止篡改,安全性高。
资源服务使用jwt可不依赖认证服务即可完成授权。
缺点:
jwt 令牌较长,占存储空间比较大
总结
到此这篇关于spring security oauth2整合jwt的详细步骤和核心配置的文章就介绍到这了,更多相关spring security oauth2整合jwt内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论