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 ...
随机推荐
- [转帖]django使用html渲染页面样式+数据库管理员的创建
一.django页面渲染 1.在templates中创建html格式的文件-index.html,在该文件中添加body,设置样式,比如: <h1 style = "backgroun ...
- [转帖]容器化 TCP Socket 缓存、接收窗口参数
https://blog.mygraphql.com/zh/notes/low-tec/network/tcp-mem/#rmem_default 最近需要支持一个单 POD 的 TCP 连接数上 1 ...
- [转帖]TiFlash DeltaTree 存储引擎设计及实现分析 - Part 1
https://tidb.net/book/book-rush/features/tiflash-code/tiflash-deltatree TiFlash 是 TiDB 的分析引擎,是 TiDB ...
- [转帖]分析redis 大key
http://www.lishuai.fun/2023/05/05/redis-bigkey/#/%E5%AE%89%E8%A3%85 redis-rdb-tools 是一个 python 的解析 r ...
- [转帖]一个Linux 内核 bug 导致的 TCP连接卡死
https://plantegg.github.io/2022/10/10/Linux%20BUG%E5%86%85%E6%A0%B8%E5%AF%BC%E8%87%B4%E7%9A%84%20TCP ...
- [转帖]Linux设备与内存单位-扇区、块、段、页(sector、block、segment、page)
每个概念是对不同的对象而言的,但它们有一定的联系 这些概念的分析背景是Linux下的内存页和磁盘结构 扇区 是硬盘等存储设备传送单位,大小一般为512B 块 是VFS和文件系统的传送单位(所以相关设备 ...
- [转帖]jmeter压力测试
使用jmeter 进行并发压力测试. 首先需要安装好jmeter,下面以widows操作平台为例: 1.确保电脑安装并配置好java环境:具体怎么下载和配置请自行百度: 2.登录jmeter官网htt ...
- Go Plugin介绍
以下内容来自官方文档. go version: 1.17.5 综述 plugin包实现了Go插件的加载和符号解析. Go插件是一个包括了可导出函数和变量的main包(可以没有main()函数),构建时 ...
- 收藏-即时通讯(IM)开源项目OpenIM-功能手册
OpenIM简介 OpenIM是由IM技术专家打造的开源即时通讯组件,也是目前最受欢迎的开源IM项目之一,目前github star近万.开发者通过集成OpenIM组件,并私有化部署服务端,可以将即时 ...
- NLP领域任务如何选择合适预训练模型以及选择合适的方案【规范建议】【ERNIE模型首选】
1.常见NLP任务 信息抽取:从给定文本中抽取重要的信息,比如时间.地点.人物.事件.原因.结果.数字.日期.货币.专有名词等等.通俗说来,就是要了解谁在什么时候.什么原因.对谁.做了什么事.有什么结 ...