Spring Boot整合JWT实现接口访问认证
最近项目组需要对外开发相关API接口,需要对外系统进行授权认证。实现流程是先给第三方系统分配appId和appSecret,第三方系统调用我getToken接口获取token,然后将token填入Authorization请求头用于访问相关API接口。
参考文章:https://blog.csdn.net/ltl112358/article/details/79507148
具体实现方式如下:
1.引入jjwt依赖
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.6.0</version>
</dependency>
2.编写Filter
用于保护受限的API接口。
package com.laoxu.easyblog.framework;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ApiFilter extends GenericFilterBean {
public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
throws IOException, ServletException {
// Change the req and res to HttpServletRequest and HttpServletResponse
final HttpServletRequest request = (HttpServletRequest) req;
final HttpServletResponse response = (HttpServletResponse) res;
// Get authorization from Http request
final String authHeader = request.getHeader("authorization");
// If the Http request is OPTIONS then just return the status code 200
// which is HttpServletResponse.SC_OK in this code
if ("OPTIONS".equals(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
chain.doFilter(req, res);
}
// Except OPTIONS, other request should be checked by JWT
else {
// Check the authorization, check if the token is started by "Bearer "
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
throw new ServletException("Missing or invalid Authorization header");
}
// Then get the JWT token from authorization
final String token = authHeader.substring(7);
try {
// Use JWT parser to check if the signature is valid with the Key "secretkey"
final Claims claims = Jwts.parser().setSigningKey("laoxu").parseClaimsJws(token).getBody();
// Add the claim to request header
request.setAttribute("claims", claims);
} catch (final SignatureException e) {
throw new ServletException("Invalid token");
}
chain.doFilter(req, res);
}
}
}
package com.laoxu.easyblog.config;
import com.laoxu.easyblog.framework.ApiFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @Description: 对指定api接口进行访问认证
* @Author laoxu
* @Date 2019/5/10 21:17
**/
@Configuration
public class ApiAuthConfig {
@Bean
public FilterRegistrationBean apiFilter() {
final FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new ApiFilter());
registrationBean.addUrlPatterns("/api/user/*");
return registrationBean;
}
}
3.编写API接口
package com.laoxu.easyblog.controller;
import com.laoxu.easyblog.framework.Result;
import com.laoxu.easyblog.framework.ResultUtil;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
/**
* @Description:
* @Author laoxu
* @Date 2019/5/10 22:04
**/
@RestController
@RequestMapping("/api")
public class TokenController {
@PostMapping("/getToken")
public Result<String> login(@RequestParam("appId") String appId, @RequestParam("appSecret") String appSecret) {
if(!("app123".equals(appId) && "123".equals(appSecret))){
return ResultUtil.fail("授权失败");
}
// Create Twt token
String jwtToken = Jwts.builder().setSubject(appId).claim("roles", "member").setIssuedAt(new Date())
.signWith(SignatureAlgorithm.HS256, "laoxu").compact();
return ResultUtil.ok(jwtToken);
}
}
package com.laoxu.easyblog.controller;
import com.laoxu.easyblog.framework.Result;
import com.laoxu.easyblog.framework.ResultUtil;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
/**
* @Description:
* @Author laoxu
* @Date 2019/5/10 22:04
**/
@RestController
@RequestMapping("/api/user")
public class ApiController {
@RequestMapping("/getUser")
public Result<String> loginSuccess() {
return ResultUtil.ok("zhangsan");
}
}
4.测试
4.1 直接访问受限接口
4.2 获取token
4.3 携带token再次访问受限接口
分类:
# Spring-Boot
标签:
springboot
, jwt
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构