若依前后端分离项目(二)Spring Security部分

一、简介

安全框架

包含两个部分:

1、认证:用户登录

2、授权:用户拥有什么权限、可以访问什么资源

二、认证流程
  1. UsernamePasswordAuthenticationToken 实现了 Authentication 接口,是 Spring Security 中用于封装用户名密码认证信息的一个类

  2. 调用AuthenticationManager的authenticate方法进行认证

  3. 因为AuthenticationManager中管理了一群Provider,所以调用的就是那一群Provider的 authenticate方法进行认证(AuthenticationManager的实现类是ProviderManager)

  4. 调用DaoAuthenticationProvider的authenticate方法进行认证(AuthenticationProvider的实现类是DaoAuthenticationProvider),获得DaoAuthenticationProvider的UserDetailService的对象,调用此对象的loaduserByUsername,查询数据库,返回UserDetails对象

  5. 通过PasswordEncoder对比UserDetails与Authentication的密码是否一致,一致则将权限设置进Authentication

代码断点调式整个流程

1、authenticationManager.authenticate

 2、ProviderManager

3、AbstractUserDetailsAuthenticationProvider

4、DaoAuthenticationProvider

5、UserDetailsServiceImpl

补充:UsernamePasswordAuthenticationToken

用于认证前的构造方法

public UsernamePasswordAuthenticationToken(Object principal, Object credentials)
  • principal:用户身份信息,一般是用户名
  • credentials:用户凭证,一般是密码

 用于认证后的构造方法

public UsernamePasswordAuthenticationToken(Object principal, Object credentials, 
                                            Collection<? extends GrantedAuthority> authorities)
  • principal:用户身份信息(通常是 UserDetails 对象)
  • credentials:凭证信息(通常不再使用,可以设置为 null
  • authorities:用户权限信息

1、认证前

login实现类

Authentication authentication = 
    new UsernamePasswordAuthenticationToken(username, password);
Authentication authenticated = authenticationManager.authenticate(authentication);
SecurityContextHolder.getContext().setAuthentication(authenticated);

2、认证后

JWT过滤器类

// 创建认证后的对象
UsernamePasswordAuthenticationToken authentication =
              new UsernamePasswordAuthenticationToken(
              userDetails, null, userDetails.getAuthorities()
              );
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
// 存入 SecurityContext
SecurityContextHolder.getContext().setAuthentication(authentication);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值