最近项目组需要对外开发相关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实现接口访问认证的更多相关文章

  1. Spring Boot初识(4)- Spring Boot整合JWT

    一.本文介绍 上篇文章讲到Spring Boot整合Swagger的时候其实我就在思考关于接口安全的问题了,在这篇文章了我整合了JWT用来保证接口的安全性.我会先简单介绍一下JWT然后在上篇文章的基础 ...

  2. Spring Boot整合Servlet,Filter,Listener,访问静态资源

    目录 Spring Boot整合Servlet(两种方式) 第一种方式(通过注解扫描方式完成Servlet组件的注册): 第二种方式(通过方法完成Servlet组件的注册) Springboot整合F ...

  3. spring boot整合JWT例子

    application.properties jwt.expire_time=3600000 jwt.secret=MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjY34DFDSS ...

  4. Spring Boot Security JWT 整合实现前后端分离认证示例

    前面两章节我们介绍了 Spring Boot Security 快速入门 和 Spring Boot JWT 快速入门,本章节使用 JWT 和 Spring Boot Security 构件一个前后端 ...

  5. Spring Boot整合实战Spring Security JWT权限鉴权系统

    目前流行的前后端分离让Java程序员可以更加专注的做好后台业务逻辑的功能实现,提供如返回Json格式的数据接口就可以.像以前做项目的安全认证基于 session 的登录拦截,属于后端全栈式的开发的模式 ...

  6. Spring Boot(十四):spring boot整合shiro-登录认证和权限管理

    Spring Boot(十四):spring boot整合shiro-登录认证和权限管理 使用Spring Boot集成Apache Shiro.安全应该是互联网公司的一道生命线,几乎任何的公司都会涉 ...

  7. Spring Boot 整合mybatis时遇到的mapper接口不能注入的问题

    现实情况是这样的,因为在练习spring boot整合mybatis,所以自己新建了个项目做测试,可是在idea里面mapper接口注入报错,后来百度查询了下,把idea的注入等级设置为了warnin ...

  8. SpringBoot系列 - 集成JWT实现接口权限认证

    会飞的污熊 2018-01-22 16173 阅读 spring jwt springboot RESTful API认证方式 一般来讲,对于RESTful API都会有认证(Authenticati ...

  9. 基于SpringSecurity和JWT的用户访问认证和授权

    发布时间:2018-12-03   技术:springsecurity+jwt+java+jpa+mysql+mysql workBench   概述 基于SpringSecurity和JWT的用户访 ...

  10. Spring Boot 整合 Shiro ,两种方式全总结!

    在 Spring Boot 中做权限管理,一般来说,主流的方案是 Spring Security ,但是,仅仅从技术角度来说,也可以使用 Shiro. 今天松哥就来和大家聊聊 Spring Boot ...

随机推荐

  1. PG数据库的离线rpm包下载

    PG数据库的离线rpm包下载 背景 周末时间研究数据库的版本. 发现PostgreSQL数据库的版本号已经变成了一年一个大版本. 兼容起来其实成本很高. 想着能够在能够上网的机器上面弄好多套数据库. ...

  2. [转帖]Linux常用的一些命令,看你知道多少?

    https://zhuanlan.zhihu.com/p/115279009 Linux中命令有很多,而Linux系统中使用命令也是它的一大特点.在Linux系统中使用命令处理问题灵活,高效,所以熟知 ...

  3. [转帖]Docker、containerd的关系

    Docker.containerd的关系 containerd囊括了单机运行一个容器时所需要的一切: 为了能够支持多种OCI Runtime,containerd 内部使用containerd-shi ...

  4. CentOS9上面使用rpm方式安装SQLServer2022的简单总结

    CentOS9上面使用rpm方式安装SQLServer2022的简单总结 下载需要的资料 下载CentOS9 Stream的安装介质 https://mirrors.bfsu.edu.cn/cento ...

  5. postman中monitor的使用

    monitor就是一个摸鱼的功能,我们把写好的接口部署到postman的web服务器中, 绑定自己的邮箱,运行结果会发送到自己的邮箱中,不用实时监控,是个非常方便 的功能(不安全) 1.crete a ...

  6. vue中使用Object.assign导致视图不响应

    可以正常响应的 <template> <div> <ul> <li class="li-item" v-for="(item,i ...

  7. 【验证码逆向专栏】某度滑块、点选、旋转验证码 v1、v2 逆向分析

    声明 本文章中所有内容仅供学习交流使用,不用于其他任何目的,不提供完整代码,抓包内容.敏感网址.数据接口等均已做脱敏处理,严禁用于商业用途和非法用途,否则由此产生的一切后果均与作者无关! 本文章未经许 ...

  8. NSSCTF Round#17 Basic CRYPTO

    Level_1 题目 Level_1.py(我把参数整理了一下,看着舒服) #真签到题 from Crypto.Util.number import bytes_to_long, getPrime f ...

  9. IQueryable和IEnumerable学习

    IQueryable和IEnumerable区别 开始了解IQueryable和IEnumerable前,我们先看一下源码 由上面的图片可以得知IQueryable接口继承自IEnumerable接口 ...

  10. 在不同电脑间同步pycharm的配置

    备份文件同步法 最传统的方法就是把配置文件备份,然后在其它电脑上通过导入的方式来恢复,这种方法在很多软件中都实测可行. 具体对应到pycharm中,可以在pycharm菜单栏file - export ...