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整合JWT实现接口访问认证的更多相关文章
- Spring Boot初识(4)- Spring Boot整合JWT
一.本文介绍 上篇文章讲到Spring Boot整合Swagger的时候其实我就在思考关于接口安全的问题了,在这篇文章了我整合了JWT用来保证接口的安全性.我会先简单介绍一下JWT然后在上篇文章的基础 ...
- Spring Boot整合Servlet,Filter,Listener,访问静态资源
目录 Spring Boot整合Servlet(两种方式) 第一种方式(通过注解扫描方式完成Servlet组件的注册): 第二种方式(通过方法完成Servlet组件的注册) Springboot整合F ...
- spring boot整合JWT例子
application.properties jwt.expire_time=3600000 jwt.secret=MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjY34DFDSS ...
- Spring Boot Security JWT 整合实现前后端分离认证示例
前面两章节我们介绍了 Spring Boot Security 快速入门 和 Spring Boot JWT 快速入门,本章节使用 JWT 和 Spring Boot Security 构件一个前后端 ...
- Spring Boot整合实战Spring Security JWT权限鉴权系统
目前流行的前后端分离让Java程序员可以更加专注的做好后台业务逻辑的功能实现,提供如返回Json格式的数据接口就可以.像以前做项目的安全认证基于 session 的登录拦截,属于后端全栈式的开发的模式 ...
- Spring Boot(十四):spring boot整合shiro-登录认证和权限管理
Spring Boot(十四):spring boot整合shiro-登录认证和权限管理 使用Spring Boot集成Apache Shiro.安全应该是互联网公司的一道生命线,几乎任何的公司都会涉 ...
- Spring Boot 整合mybatis时遇到的mapper接口不能注入的问题
现实情况是这样的,因为在练习spring boot整合mybatis,所以自己新建了个项目做测试,可是在idea里面mapper接口注入报错,后来百度查询了下,把idea的注入等级设置为了warnin ...
- SpringBoot系列 - 集成JWT实现接口权限认证
会飞的污熊 2018-01-22 16173 阅读 spring jwt springboot RESTful API认证方式 一般来讲,对于RESTful API都会有认证(Authenticati ...
- 基于SpringSecurity和JWT的用户访问认证和授权
发布时间:2018-12-03 技术:springsecurity+jwt+java+jpa+mysql+mysql workBench 概述 基于SpringSecurity和JWT的用户访 ...
- Spring Boot 整合 Shiro ,两种方式全总结!
在 Spring Boot 中做权限管理,一般来说,主流的方案是 Spring Security ,但是,仅仅从技术角度来说,也可以使用 Shiro. 今天松哥就来和大家聊聊 Spring Boot ...
随机推荐
- [转帖]MySQL 8.2.0 GA
https://cloud.tencent.com/developer/article/2353798 MySQL新的进化版8.2.0于2023年10月25日发行,让我们一起快速浏览一下该版本发生哪些 ...
- [转帖]TiFlash 面向编译器的自动向量化加速
作者:朱一帆 目录 SIMD 介绍 SIMD 函数派发方案 面向编译器的优化 SIMD 介绍 SIMD 是重要的重要的程序加速手段.CMU DB 组在 Advanced Database Syst ...
- [转帖]实战演练 | Navicat 数据生成功能
https://zhuanlan.zhihu.com/p/631823381 数据生成的目的是依据某个数据模型,从原始数据通过计算得到目标系统所需要的符合该模型的数据.数据生成与数据模型是分不开的,数 ...
- 【转帖】nginx变量使用方法详解-2
https://www.diewufeiyang.com/post/576.html 关于 Nginx 变量的另一个常见误区是认为变量容器的生命期,是与 location 配置块绑定的.其实不然.我们 ...
- [转帖]Nacos 获取配置时启用权限认证
默认情况下获取 Nacos 中的配置是不需要权限认证的, 这个估计是由其使用场景决定的(绝大多数都是仅内网可访问). 今天调查了下如何在获取配置时增加权限验证以提高其安全性. 1. 启用 Nacos ...
- [转帖]Intel甘拜下风,挤牙膏比不过兆芯CPU
https://baijiahao.baidu.com/s?id=1735997557665412214 本文比较长,有万字左右,因此在前面先把小标题集中亮个相. 即使大家一晃而过,我也要让精心拟 ...
- Flask闪现
目录 九.闪现 9.1 什么是闪现? 九.闪现 9.1 什么是闪现? -设置:flash('aaa') -取值:get_flashed_message() - -假设在a页面操作出错,跳转到b页面,在 ...
- TienChin 活动管理-添加活动接口
ActivityController @PreAuthorize("hasPermission('tienchin:activity:create')") @Log(title = ...
- 14.4 Socket 双向数据通信
所谓双向数据传输指的是客户端与服务端之间可以无差异的实现数据交互,此类功能实现的核心原理是通过创建CreateThread()函数多线程分别接收和发送数据包,这样一旦套接字被建立则两者都可以异步发送消 ...
- Python 实现 WebSocket 通信
WebSocket 协议主要用于解决Web前端与后台数据交互问题,在WebSocket技术没有被定义之前,前台与后端通信需要使用轮询的方式实现,WebSocket则是通过握手机制让客户端与服务端建立全 ...