6.鉴权

简介: aegheadhbdawbhwshb

1.客户端Token方案
1.1 实现思路

简单客户端token校验.vsdx(57 KB)

客户端

服务端

用户

1.发起请求

2.登录验证

3.验证登陆账户是否

正确,正确则生成

token,redis满存并返

4响应结果

5.验证登陆是否成功

6登陆失败,系统汽宋-

循环

7.携带token请求接口

8.过滤器验证token是

否正确,正确允许接

口,请求否错误提

系统维末



1.2 实现细节
参考:https://www.cnblogs.com/dalaoyang/p/11783225.html
2.JWT + Security
RFC7519
JWT

JWT很大程度上还是个新技术,通过使用HMAC(Hash-based Message Authentication Code)计算信息摘要,也可以用RSA公私钥中的私钥进行签名。这个根据业务场景进行选择。
2.1 pom依赖
在/login进行登录并获得Token。剩余接口做token验签,这里我们需要将spring-boot-starter-security加入pom.xml。加入后,我们的Spring Boot项目将需要提供身份验证,相关的pom.xml如下:

至此我们剩余所有的路由都需要身份验证。我们将引入一个安全设置类WebSecurityConfig,这个类需要从WebSecurityConfigurerAdapter类继承。
2.2 安全设置类WebSecurityConfig


先放两个基本类,一个负责存储用户名密码,另一个是一个权限类型,负责存储权限和角色。
2.3 权限类型及角色类
2.4 用户名密码类


在上面的安全设置类中,我们设置所有人都能访问/和POST方式访问/login,其他的任何路由都需要进行认证。然后将所有访问/login的请求,都交给JWTLoginFilter过滤器来处理。稍后我们会创建这个过滤器和其他这里需要的JWTAuthenticationFilter和CustomAuthenticationProvider两个类。
2.5 JWT生成及验签类


这个类就两个static方法,一个负责生成JWT,一个负责认证JWT最后生成验证令牌。注释已经写得很清楚了,这里不多说了。
下面来看自定义验证组件,这里简单写了,这个类就是提供密码验证功能,在实际使用时换成自己相应的验证逻辑,从数据库中取出、比对、赋予用户相应权限。
2.6 自定义验证组件类


2.7 接口类

下面实现JWTLoginFilter 这个Filter比较简单,除了构造函数需要重写三个方法。
attemptAuthentication - 登录时需要验证时候调用
successfulAuthentication - 验证成功后调用
unsuccessfulAuthentication - 验证失败后调用,这里直接灌入500错误返回,由于同一JSON返回,HTTP就都返回200了

2.8 JWTLoginFilter

Java

运行代码复制代码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

import com.fasterxml.jackson.databind.ObjectMapper;

import com.test.framework.client.dto.response.JSONResultDTO;

import com.test.framework.web.domain.vo.AccountCredentials;

import org.springframework.security.authentication.AuthenticationManager;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;

import org.springframework.security.core.Authentication;

import org.springframework.security.core.AuthenticationException;

import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;

import org.springframework.security.web.util.matcher.AntPathRequestMatcher;


import javax.servlet.FilterChain;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;


class JWTLoginFilter extends AbstractAuthenticationProcessingFilter {

public JWTLoginFilter(String url, AuthenticationManager authManager) {

super(new AntPathRequestMatcher(url));

setAuthenticationManager(authManager);

}

   @Override

public Authentication attemptAuthentication(

HttpServletRequest req, HttpServletResponse res)

throws AuthenticationException, IOException, ServletException {

// JSON反序列化成 AccountCredentials

AccountCredentials creds = new ObjectMapper().readValue(req.getInputStream(), AccountCredentials.class);

// 返回一个验证令牌

return getAuthenticationManager().authenticate(

new UsernamePasswordAuthenticationToken(

creds.getUsername(),

creds.getPassword()

)

);

}

   @Override

protected void successfulAuthentication(

HttpServletRequest req,

HttpServletResponse res, FilterChain chain,

Authentication auth) throws IOException, ServletException {

TokenAuthenticationService.addAuthentication(res, auth.getName());

}

   @Override

protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {

response.setContentType("application/json");

response.setStatus(HttpServletResponse.SC_OK);

response.getOutputStream().println(JSONResult.fillResultString(500, "Internal Server Error!!!", JSONObject.NULL));

}

}


再完成最后一个类JWTAuthenticationFilter,这也是个拦截器,它拦截所有需要JWT的请求,然后调用TokenAuthenticationService类的静态方法去做JWT验证。

2.9 拦截器JWTAuthenticationFilter

Java

运行代码复制代码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

import org.springframework.security.core.Authentication;

import org.springframework.security.core.context.SecurityContextHolder;

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 java.io.IOException;


class JWTAuthenticationFilter extends GenericFilterBean {

   @Override

public void doFilter(ServletRequest request,

ServletResponse response,

FilterChain filterChain)

throws IOException, ServletException {

Authentication authentication = TokenAuthenticationService

.getAuthentication((HttpServletRequest)request);

SecurityContextHolder.getContext()

.setAuthentication(authentication);

filterChain.doFilter(request,response);

}

}


现在代码就写完了,整个Spring Security结合JWT基本就差不多了,下面我们来测试下,并说下整体流程。
开始测试,先运行整个项目,这里介绍下过程:
先程序启动 - main函数
注册验证组件 - WebSecurityConfig 类 configure(AuthenticationManagerBuilder auth)方法,这里我们注册了自定义验证组件
设置验证规则 - WebSecurityConfig 类 configure(HttpSecurity http)方法,这里设置了各种路由访问规则
初始化过滤组件 - JWTLoginFilter 和 JWTAuthenticationFilter 类会初始化

相关文章
|
存储 安全 Java
Spring Boot整合Spring Security--学习笔记
Spring Boot整合Spring Security--学习笔记
443 1
Vue3 跨组件传参 provide 与 inject
Vue3 跨组件传参 provide 与 inject
275 0
|
存储 安全 数据安全/隐私保护
Token 是什么?全面解析身份认证中的 Token 机制
本文全面解析Token在身份认证中的核心机制,涵盖JWT、Session Token、OAuth等类型,深入讲解其工作原理、安全性策略、生命周期管理及实际应用场景,助力开发者构建安全高效的现代Web应用认证体系。
4452 3
|
4月前
|
存储 负载均衡 算法
|
4月前
|
XML JSON Java
|
4月前
|
uml C语言
系统时序图
时序图(Sequence Diagram)是UML中描述对象间消息传递时间顺序的交互图。横轴为对象,纵轴为时间,通过消息展示动态协作过程,强调交互的时间次序,可用于建模并发行为。主要元素包括角色、对象、生命线、控制焦点和各类消息,直观呈现系统运行流程。
|
4月前
|
项目管理 开发者
业务架构图
本文介绍了业务架构图的核心概念与绘制方法,涵盖业务定义、架构分层(业务应用层、能力层、基础层等)、模块与功能划分,并以医疗场景为例,展示如何通过分层分模块构建清晰的业务视图,提升客户理解与开发效率。
|
存储 安全 Java
详解 Spring Security:全面保护 Java 应用程序的安全框架
详解 Spring Security:全面保护 Java 应用程序的安全框架
980 1
|
存储 安全 Java
什么是 PasswordEncoder?
【8月更文挑战第21天】
681 0
|
缓存 安全 Java
【权限管理系统】Spring security(三)---认证过程(原理解析,demo)
【权限管理系统】Spring security(三)---认证过程(原理解析,demo)