spring security+jwt实现前后端分离权限控制实战
在前后端分离项目中,传统的基于 session 的认证方式已不再适用。取而代之的是更加轻量、高效的 jwt(json web token)方式来实现无状态认证。
一、为什么要用 jwt?
前后端分离架构的挑战:
- 无法使用 session 管理登录状态(前端和后端分离、跨域)
- 需要一种「无状态认证机制」
jwt 的优势:
- 无需在服务端存储会话信息(token 自包含)
- 结构清晰,支持权限声明(claims)
- 可扩展性强,可用于 oauth、sso 等场景
二、jwt 基本结构
一个 jwt token 一般分为三段:
header.payload.signature
例如:
eyjhbgcioijiuzi1nij9.eyjzdwiioij1c2vyiiwiawf0ijoxnjg3njq5fq.k4kgd1se0jqza1k6k-fasd56fq
每部分作用:
| 部分 | 内容 |
|---|---|
| header | 签名算法,如 hs256 |
| payload | 载荷(如用户名、角色、过期时间) |
| signature | 签名(防止篡改) |
三、集成 jwt 的 spring security 权限控制思路
整体流程如下:
前端登录 -> 后端验证用户 -> 生成 jwt -> 返回给前端 -> 前端每次请求携带 token -> 后端解析验证并授权
四、核心模块代码实战
1. 引入依赖(spring boot 3.x 示例)
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-security</artifactid>
</dependency>
<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>2. jwt 工具类
@component
public class jwtutil {
private final string secret = "myjwtsecretkey123"; // 建议放到配置文件中
private final long expiration = 1000 * 60 * 60; // 1小时
public string generatetoken(string username) {
return jwts.builder()
.setsubject(username)
.setissuedat(new date())
.setexpiration(new date(system.currenttimemillis() + expiration))
.signwith(signaturealgorithm.hs256, 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;
}
}
}3. 自定义登录接口生成 token
@restcontroller
public class authcontroller {
@autowired
private authenticationmanager authenticationmanager;
@autowired
private jwtutil jwtutil;
@postmapping("/login")
public responseentity<?> login(@requestbody loginrequest loginrequest) {
try {
authentication auth = authenticationmanager.authenticate(
new usernamepasswordauthenticationtoken(loginrequest.getusername(), loginrequest.getpassword())
);
string token = jwtutil.generatetoken(loginrequest.getusername());
return responseentity.ok(collections.singletonmap("token", token));
} catch (authenticationexception e) {
return responseentity.status(httpstatus.unauthorized).body("用户名或密码错误");
}
}
}4. jwt 认证过滤器
@component
public class jwtauthfilter extends onceperrequestfilter {
@autowired
private jwtutil jwtutil;
@autowired
private userdetailsservice userdetailsservice;
@override
protected void dofilterinternal(httpservletrequest request, httpservletresponse response, filterchain chain)
throws servletexception, ioexception {
string authheader = request.getheader("authorization");
if (authheader != null && authheader.startswith("bearer ")) {
string token = authheader.substring(7);
string username = jwtutil.getusernamefromtoken(token);
if (username != null && securitycontextholder.getcontext().getauthentication() == null) {
userdetails userdetails = userdetailsservice.loaduserbyusername(username);
if (jwtutil.validatetoken(token)) {
usernamepasswordauthenticationtoken authtoken =
new usernamepasswordauthenticationtoken(userdetails, null, userdetails.getauthorities());
authtoken.setdetails(new webauthenticationdetailssource().builddetails(request));
securitycontextholder.getcontext().setauthentication(authtoken);
}
}
}
chain.dofilter(request, response);
}
}5. 配置 securityfilterchain
@configuration
@enablemethodsecurity
public class securityconfig {
@autowired
private jwtauthfilter jwtauthfilter;
@bean
public securityfilterchain filterchain(httpsecurity http) throws exception {
return http
.csrf(csrf -> csrf.disable())
.authorizehttprequests(auth -> auth
.requestmatchers("/login").permitall()
.anyrequest().authenticated()
)
.sessionmanagement(session -> session.sessioncreationpolicy(sessioncreationpolicy.stateless))
.addfilterbefore(jwtauthfilter, usernamepasswordauthenticationfilter.class)
.build();
}
@bean
public authenticationmanager authenticationmanager(authenticationconfiguration config) throws exception {
return config.getauthenticationmanager();
}
}五、前端如何配合使用?
- 登录后保存返回的
token - 所有后续请求在 header 中添加:
authorization: bearer <你的 token>
六、权限控制示例
@restcontroller
public class usercontroller {
@preauthorize("hasrole('admin')")
@getmapping("/admin/data")
public string admindata() {
return "管理员数据";
}
@preauthorize("hasanyrole('user','admin')")
@getmapping("/user/data")
public string userdata() {
return "用户数据";
}
}总结
jwt 与 spring security 的结合,可以帮助你构建一个无状态、安全、高效的前后端分离权限系统。它简化了登录状态的管理流程,提高了系统的伸缩性与并发处理能力。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论