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 ...
随机推荐
- [转帖]rsync原理
简介: Rsync(remote synchronize)是一个远程数据同步工具,可通过LAN/WAN快速同步多台主机间的文件.Rsync使用所谓的"Rsync算法"来使本地和远 ...
- [转帖]Shell三剑客之awk
目录 awk简述 awk的工作过程 awk的工作原理 awk的基本格式及其内置变量 getline 文本内容匹配过滤打印 对字段进行处理打印 条件判断打印 awk的三元表达式与精准筛选用法 awk的精 ...
- [转帖]使用 BR 命令行备份恢复
TiDB试用 来源:TiDB 浏览 404 扫码 分享 2021-04-20 20:49:42 使用 BR 命令行进行备份恢复 BR 命令行描述 命令和子命令 常用选项 使用 BR 命令行备份集群数 ...
- [转帖]arm linux下编译xtrabackup-2.4.5
环境:aarch64/centos7.6 glibc-2.17 编译器:gcc version 5.5.0 (GCC) 官方参考文档:https://www.percona.com/doc/perc ...
- [转帖]优化超大 Nginx 配置导致的内存碎片
https://blog.openresty.com.cn/cn/ngx-cycle-pool-frag/?src=org_news 章亦春发布于 Feb 14, 2023更新于 Mar 2, 202 ...
- [转帖]016 Linux 卧槽,看懂进程信息也不难嘛?top、ps
016 Linux 卧槽,看懂进程信息也不难嘛?top.pshttps://my.oschina.net/u/3113381/blog/5455267 1 扒开看看 top 命令参数详情 Linux ...
- 《Javascript高级程序设计》读书笔记——构造函数与原型
构造函数与原型 构造函数模式 最简单的构造函数: function Person(name, age, job) { this.name = name; this.age = age; this.jo ...
- 2023年了,做SEO还有必要吗?
作者:京东科技 吴磊 搜索引擎工作原理 在搜索引擎网站的后台会有一个非常庞大的数据库,里面存储了海量的关键词,而每个关键词又对应着很多网址,这些网址是被称之为"搜索引擎蜘蛛"或&q ...
- JAVA多线程并发编程-避坑指南
作者:京东零售 肖朋伟 一.前言 开发过程中,多线程的应用场景可谓十分广泛,可以充分利用服务器资源,提高程序处理速度.我们通常也会使用池化技术,去避免频繁创建和销毁线程. 本篇旨在基于编码规范.工作中 ...
- NOI2023 游记
不完全按时间顺序写.记录 NOI 的一些琐事. 从 XDFZ 坐大巴 5 个小时来到成七.第一眼看到的是一个放着 NOI 牌子的台阶,还有一个签名墙.好像在我们之前到的人不太多? 用中英双语签名(冷月 ...