springboot集成jwt实现无状态身份认证实战
在现代web应用中,身份认证是必不可少的安全环节。传统的基于session的认证方式虽然简单易用,但在微服务架构和前端多平台场景下,面临着扩展性差和服务器存储压力大等问题。本文将介绍如何在springboot项目中集成jwt(json web token)实现无状态的身份认证方案。
一、什么是jwt
jwt是一种开放标准(rfc 7519),定义了一种紧凑且自包含的方式,用于在各方之间安全传输信息作为json对象。jwt由三部分组成:
1. **header**:包含令牌类型和使用的哈希算法
2. **payload**:存放有效信息的负载部分
3. **signature**:对前两部分进行签名,防止数据篡改
典型的jwt格式:`xxxxx.yyyyy.zzzzz`
二、springboot集成jjwt
首先,在pom.xml中添加jjwt依赖:
<dependency> <groupid>io.jsonwebtoken</groupid> <artifactid>jjwt-api</artifactid> <version>0.11.5</version> </dependency> <dependency> <groupid>io.jsonwebtoken</groupid> <artifactid>jjwt-impl</artifactid> <version>0.11.5</version> <scope>runtime</scope> </dependency> <dependency> <groupid>io.jsonwebtoken</groupid> <artifactid>jjwt-jackson</artifactid> <version>0.11.5</version> <scope>runtime</scope> </dependency>
创建jwt工具类`jwtutils.java`:
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.keys;
import org.springframework.beans.factory.annotation.value;
import org.springframework.stereotype.component;
import javax.crypto.secretkey;
import java.util.date;
import java.util.hashmap;
import java.util.map;
@component
public class jwtutils {
@value("${jwt.secret}")
private string secret;
@value("${jwt.expiration}")
private long expiration;
// 生成token
public string generatetoken(string username) {
map<string, object> claims = new hashmap<>();
secretkey key = keys.hmacshakeyfor(secret.getbytes());
return jwts.builder()
.setclaims(claims)
.setsubject(username)
.setissuedat(new date())
.setexpiration(new date(system.currenttimemillis() + expiration * 1000))
.signwith(key, signaturealgorithm.hs256)
.compact();
}
// 解析token获取用户名
public string getusernamefromtoken(string token) {
secretkey key = keys.hmacshakeyfor(secret.getbytes());
return jwts.parserbuilder()
.setsigningkey(key)
.build()
.parseclaimsjws(token)
.getbody()
.getsubject();
}
// 验证token是否有效
public boolean validatetoken(string token) {
try {
secretkey key = keys.hmacshakeyfor(secret.getbytes());
jwts.parserbuilder().setsigningkey(key).build().parseclaimsjws(token);
return true;
} catch (exception e) {
return false;
}
}
}三、实现认证拦截器
创建jwt认证拦截器`jwtauthenticationfilter.java`:
@component
public class jwtauthenticationfilter extends onceperrequestfilter {
@autowired
private jwtutils jwtutils;
@override
protected void dofilterinternal(httpservletrequest request,
httpservletresponse response,
filterchain chain)
throws servletexception, ioexception {
string token = request.getheader("authorization");
// 如果请求头中没有token,直接放行
if (stringutils.isempty(token)) {
chain.dofilter(request, response);
return;
}
// 验证token有效性
if (!jwtutils.validatetoken(token)) {
response.setstatus(httpstatus.unauthorized.value());
response.getwriter().write("无效的token");
return;
}
// 获取用户名并设置到securitycontext中
string username = jwtutils.getusernamefromtoken(token);
usernamepasswordauthenticationtoken authentication =
new usernamepasswordauthenticationtoken(username, null, new arraylist<>());
securitycontextholder.getcontext().setauthentication(authentication);
chain.dofilter(request, response);
}
}配置拦截器注册:
@configuration
public class websecurityconfig extends websecurityconfigureradapter {
@autowired
private jwtauthenticationfilter jwtauthenticationfilter;
@override
protected void configure(httpsecurity http) throws exception {
http.csrf().disable()
.authorizerequests()
.antmatchers("/api/auth/**").permitall()
.anyrequest().authenticated()
.and()
.addfilterbefore(jwtauthenticationfilter, usernamepasswordauthenticationfilter.class);
}
}四、前后端交互流程
1. **登录流程**:
- 客户端发送用户名密码到`/api/auth/login`
- 服务器验证成功后生成jwt返回给客户端
- 客户端将jwt存储在本地(localstorage或cookie)
2. **后续请求**:
- 客户端在请求头中添加`authorization: bearer <jwt>`
- 服务器验证jwt有效性后处理请求
五、注意事项
1. **安全性**:
- 必须使用https传输jwt
- 设置较短的过期时间,结合refresh token实现自动续期
- jwt一旦发出无法撤回,处理敏感操作应额外验证密码
2. **性能优化**:
- 避免在jwt中存储过多信息
- 可以考虑将部分用户信息缓存在redis中
3. **常见问题**:
- 密钥泄露问题:定期更换密钥
- csrf攻击:配合csrf token使用
通过本文介绍的方案,我们可以在springboot项目中轻松实现基于jwt的无状态认证。相比传统session验证,jwt方案更适合现代分布式系统的认证需求,具有诸多优势。
到此这篇关于springboot集成jwt无状态身份认证的文章就介绍到这了,更多相关springboot jwt无状态身份认证内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论