springsecurity登录授权的实现过程

Spring Security是什么

Spring Security是Spring项目组提供的安全服务框架,核心功能包 括认证授权。它为系统提供了声明式安全访问控制功能,减少了 为系统安全而编写大量重复代码的工作。

认证

认证即系统判断用户的身份是否合法,合法可继续访问,不合法则 拒绝访问。 认证是为了保护系统的隐私数据与资源,用户的身份合法才能访问 该系统的资源。

授权

授权即认证通过后,根据用户的权限来控制用户访问资源的过程, 拥有资源的访问权限则正常访问,没有权限则拒绝访问。 比如在一 些视频网站中,普通用户登录后只有观看免费视频的权限,而VIP用 户登录后,网站会给该用户提供观看VIP视频的权限。 认证是为了保证用户身份的合法性,授权则是为了更细粒度的对隐 私数据进行划分,控制不同的用户能够访问不同的资源。

实现思路:

登录:

①自定义登录接口

调用ProviderManager的方法进行认证 如果认证通过生成jwt

把用户信息存进redis中

②自定义UserDetailsService

在这个实现类中查询数据

校验

①定义jwt过滤器

获取token

解析token获取其中的userid

从redis中获取用户数据

存入SecurityContextHolder

Springsecurity认证流程(过滤器链的使用)

名词解释:

Authentication接口: 它的实现类,表示当前访问系统的用户,封装了用户相关信息。

AuthenticationManager接口:定义了认证Authentication的方法

UserDetailsService接口:加载用户特定数据的核心接口。里面定义了一个根据用户名查询用户信息的 方法。

UserDetails接口:提供核心用户信息。通过UserDetailsService根据用户名获取处理的用户信息要封装 成UserDetails对象返回。然后将这些信息封装到Authentication对象中。

自定义登录接口的实现流程:

  1. 先使用继承UserDetailsService实体类,利用数据库查询到的用户数据封装到自定义的实体类中,该实体类继承了UserDetails,系统会自动调用getpaword等方法进行账户密码的比对。

  2. 自定义登录接口,在配置类中声明对该接口放行,在该接口中通过AuthenticationManager的authenticate方法来进行用户认证(即上文1的自定义认证方法),通过则放回jwt令牌

  3. 加入过滤器,通过对token的解析判断用户是否登录

实现步骤

引入依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
实现UserDetailsService接口

实现UserDetailService接口并重写loadUserByUsername方法,在该方法中利用用户名对数据库进行查询将查询到的数据封装到LoginUser中,LoginUser是继承UserDetails的实体类,用于封装数据库查询的信息,security的内部会调用其getpassword()方法等获取其信息与前端输入的数据进行对比。

LoginUser实体类

@Data
@NoArgsConstructor
@AllArgsConstructor
public class LoginUser implements UserDetails {
    private Emp user;
​
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return null;
    }
​
    // 改写函数 返回用户名密码
    @Override
    public String getPassword() {
        return user.getPassword();
    }
​
    @Override
    public String getUsername() {
        return user.getUsername();
    }
​
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }
​
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }
​
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
​
    @Override
    public boolean isEnabled() {
        return true;
    }
}
​

继承UserDetailsService实体类

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
​
    @Autowired
    private EmpMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        Emp emp = userMapper.selectUser(username);
        if (Objects.isNull(emp)){
            throw new RuntimeException("用户名或密码错误");
        }
​
        // TODO 查询用户的授权信息
​
        // LoginUser是继承UserDetails的实体类 封装自定义返回对象
        return new LoginUser(emp);
    }
}
密码加密 密文形式显示

默认使用的PasswordEncoder要求数据库中的密码格式为:{id}password 。它会根据id去判断密码的 加密方式。但是我们一般不会采用这种方式,所以自定义登录时密码不匹配,所以就需要替换PasswordEncoder。

一般是替换成SpringSecurity为我们提供的BCryptPasswordEncoder。

注意:替换成功时我们要确保数据库中存储的格式是通过BCryptPasswordEncoder加密的密文显示格式,所以在用户注册方面我们应实现密码的加密存储

改写SpringSecurity的原有密码格式,只需添加一个配置类,按照springsecurity的要求该类要继承WebSecurityConfigurerAdapter。原有的WebSecurityConfigurerAdapter已经过时了,故要添加@EnableGlobalMethodSecurity(prePostEnabled = true) 注解开启其作用。

配置类如下:

@Configuration
//@EnableWebSecurity  // 代替继承WebSecurityConfigurerAdapter
// 使用该注解开启WebSecurityConfigurerAdapter
@EnableGlobalMethodSecurity(prePostEnabled = true) 
public class securityConfig  extends WebSecurityConfigurerAdapter {
​
    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
​
    // 创建BCryptPasswordEncoder注入容器 代替原有的密码加密方式
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
​
}
​
自定义登录接口
  @Autowired
    private SecurityLoginSercive securityLoginSercive;
​
    @PostMapping("/login")
    public Result login(@RequestBody Emp emp){
        log.info("开始登录请求:" + emp.toString());
        String token = securityLoginSercive.login(emp);
        return Result.success(token);
    }
实现登录逻辑:

利用authenticationManager.authenticate(authenticationToken);方法开启系统的认证,springsecrity会自动调用我们上文书写的认证方法进行认证,认证成功后返回token并将用户信息存入redis中

UsernamePasswordAuthenticationToken继承AbstractAuthenticationToken实现Authentication所以当在页面中输入用户名和密码之后首先会进入到UsernamePasswordAuthenticationToken验证(Authentication),然后生成的Authentication会被交由AuthenticationManager来进行管理而AuthenticationManager管理一系列AuthenticationProvider,而每一个Provider都会通UserDetailsService和UserDetail来返回一个 以UsernamePasswordAuthenticationToken实现的带用户名和密码以及权限的Authentication

UsernamePasswordAuthenticationToken 是 Spring Security 中用于封装用户名密码认证信息的一个类,它实现了 Authentication 接口,用于表示一个认证请求。它的构造方法如下

public UsernamePasswordAuthenticationToken(Object principal, Object credentials);

其中,principal 是认证的主体信息,通常为用户名或者用户对象;credentials 是认证的凭证信息,通常为密码或者其他类似信息。在构造时,还可以使用其他构造方法为认证请求设置授权信息、权限列表等。

在 Spring Security 中,通过 AuthenticationManager 对象对认证请求进行认证,认证成功后会生成一个 Authentication 对象,并将其存储在 SecurityContextHolder 中,用于表示当前的认证信息。在应用程序中,可以通过 SecurityContextHolder 对象获取当前的认证信息。

@Service
@Slf4j
public class SecurityLoginSerciveImpl implements SecurityLoginSercive {
​
    // 注入AuthenticationManager对象 开启自定义验证
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public String login(Emp user) {
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUsername()
                        , user.getPassword());
       log.info("自定义验证前");
        // 开启自定义验证
        Authentication authenticate =
                authenticationManager.authenticate(authenticationToken);
        log.info("自定义验证后");
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }
        // 使用userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        // 自定义数据载荷封装进Token里面
        String userId = loginUser.getUser().getId().toString();
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constant.userId, userId);
        String token = JwtUtils.generateJwt(claims);
​
        // 将authenticate存入redis
        redisTemplate.opsForValue().set(Constant.redisKeyPre + userId, loginUser);
​
        return token;
    }
​
    @Override
    /**
     * 退出登录
     */
    public void logout() {
        Authentication authentication =
                SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String userId = String.valueOf(loginUser.getUser().getId());
        redisTemplate.delete(Constant.redisKeyPre + userId);
    }
自定义配置类:不拦截自定义的登录接口
@Configuration
//@EnableWebSecurity  // 代替继承WebSecurityConfigurerAdapter
@EnableGlobalMethodSecurity(prePostEnabled = true)  // 使用该注解开启WebSecurityConfigurerAdapter
public class securityConfig  extends WebSecurityConfigurerAdapter {
​
    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
​
    // 创建BCryptPasswordEncoder注入容器 代替原有的密码加密方式
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
​
    @Bean
    @Override
    // 对用户的未授信凭据进行认证,认证通过则返回授信状态的凭据,否则将抛出认证异常AuthenticationException
    public AuthenticationManager authenticationManagerBean() throws Exception{
        return super.authenticationManagerBean();
    }
​
//    配置 HttpSecurity 。 HttpSecurity 用于构建一个安全过滤器链 SecurityFilterChain
//    SecurityFilterChain 最终被注入核心过滤器
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            //关闭csrf
            .csrf().disable()
            //不通过Session获取SecurityContext
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            // 对于登录接口 允许匿名访问
            .antMatchers("/login").anonymous()
            // 除上面外的所有请求全部需要鉴权认证
            .anyRequest().authenticated();
​
        // 添加token校验的过滤器到过滤器链中
        http.addFilterBefore(jwtAuthenticationTokenFilter,
                UsernamePasswordAuthenticationFilter.class);
    }
​
​
}
自定义认证过滤器

我们需要自定义一个过滤器,这个过滤器会去获取请求头中的token,对token进行解析取出其中的 userid。 使用userid去redis中获取对应的LoginUser对象。 然后封装Authentication对象存入SecurityContextHolder

注意:添加的过滤器要在上文的springsecurity中添加自定义的认证过滤器到过滤器链中,添加的位置是在所有的过滤器之前

@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取token
        String token = request.getHeader("token");
        // 如果不存在先放行 后面过滤器会自动识别是否是认证状态
        if(!StringUtils.hasText(token)){
            log.info("用户未登录");
            // 创建响应对象
            Result responseResult = Result.error("NOT_LOGIN");

            // 把Result对象转换为Json数据
            String json = JSONObject.toJSONString(responseResult);
            // 设置响应头告知浏览器
            response.setContentType("application/json; charset=utf-8");

            // 响应
            response.getWriter().write(json);

            // 放行
//            filterChain.doFilter(request, response);
            return;
        }

        // 解析token
        String userid;
        try {
            Claims claims = JwtUtils.parseJWT(token);
            userid = (String) claims.get(Constant.userId);
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }

        // 查询redis信息
        String redisKey = Constant.redisKeyPre + userid;
        LoginUser loginUser = (LoginUser) redisTemplate.opsForValue().get(redisKey);
        if (Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录");
        }

        // 存入SecurityContextHolder
        //TODO 获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        // 放行
        filterChain.doFilter(request, response);


    }
}

2、授权

2.0 权限系统的作用

例如一个学校图书馆的管理系统,如果是普通学生登录就能看到借书还书相关的功能,不可能让他看到 并且去使用添加书籍信息,删除书籍信息等功能。但是如果是一个图书馆管理员的账号登录了,应该就 能看到并使用添加书籍信息,删除书籍信息等功能。

总结起来就是不同的用户可以使用不同的功能。这就是权限系统要去实现的效果。

我们不能只依赖前端去判断用户的权限来选择显示哪些菜单哪些按钮。因为如果只是这样,如果有人知 道了对应功能的接口地址就可以不通过前端,直接去发送请求来实现相关功能操作。 所以我们还需要在后台进行用户权限的判断,判断当前用户是否有相应的权限,必须具有所需权限才能 进行相应的操作。

2.1 授权基本流程

在SpringSecurity中,会使用默认的FilterSecurityInterceptor来进行权限校验。在 FilterSecurityInterceptor中会从SecurityContextHolder获取其中的Authentication,然后获取其中的 权限信息。当前用户是否拥有访问当前资源所需的权限。 所以我们在项目中只需要把当前登录用户的权限信息也存入Authentication。 然后设置我们的资源所需要的权限即可。

2.2 授权的实现

2.2.1 限制访问资源所需权限

1、先在自定义的springsecurity配置类中添加注解开启权限访问功能

@EnableGlobalMethodSecurity(prePostEnabled = true)

2、在对应的controller接口中添加注解@PreAuthorize及其访问的权限

@PreAuthorize("hasAnyAuthority()")为开启权限的注解及调用的方法,system:dept:list为用户应该具备的权限

      @GetMapping("/depts")
    //    @PreAuthorize("hasAnyAuthority()") 为开启权限访问的注解
    // system:dept:list为权限的标识
    @PreAuthorize("hasAnyAuthority('system:dept:list')")
    public Result list(){
        log.info("查询到所有部门");
        List<Dept> deptList = deptService.list();
        return Result.success(deptList);
    }
2.2.2 封装权限信息

我们前面在写UserDetailsServiceImpl的时候说过,在查询出用户后还要获取对应的权限信息,封装到 UserDetails中返回。因此我们要修改之前定义了UserDetails的实现类LoginUser,让其能封装权限信息并进行返回。

修改UserDetails的实现类LoginUser,添加权限字段,并重写getAuthorities返回对应的权限标识,注意添加权限字段后要重写LoginUser类的有参构造

@Data
@NoArgsConstructor
public class LoginUser implements UserDetails {
    private Emp user;

    // 存储权限字段
    private List<String> permissions;

    //存储SpringSecurity所需要的权限信息的集合
    // 封装用户权限的放回集合,避免每次登录都要创建其对象
    // @JSONField(serialize = false) 不参与用户序列化 GrantedAuthority类型是不能被序列化的
    @JSONField(serialize = false)
    private List<GrantedAuthority> authorities;

    /**
     * 重写getAuthorities方法注入用户权限
     * 把permissions中字符串类型的权限信息转换成GrantedAuthority对象存入authorities中
     * @return
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (authorities != null){
            return authorities;
        }
        authorities = permissions
                .stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
        return authorities;
    }

    // 改写有参构造
    public LoginUser(Emp user,List<String> permissions) {
        this.user = user;
        this.permissions = permissions;
    }

    // 改写函数 返回用户名密码
    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
在token认证过滤器中封装权限认证信息 loginUser.getAuthorities();
 UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());

token认证的源码如下:

@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取token
        String token = request.getHeader("token");
        // 如果不存在先放行 后面过滤器会自动识别是否是认证状态
        // 此次必须放行 如果不放行用户将无法登录
        if(!StringUtils.hasText(token)){
            log.info("用户未登录");
//            // 创建响应对象
//            Result responseResult = Result.error("NOT_LOGIN");
//
//            // 把Result对象转换为Json数据
//            String json = JSONObject.toJSONString(responseResult);
//            // 设置响应头告知浏览器
//            response.setContentType("application/json; charset=utf-8");
//
//            // 响应
//            response.getWriter().write(json);

            // 放行
            filterChain.doFilter(request, response);
            return;
        }

        // 解析token
        String userid;
        try {
            Claims claims = JwtUtils.parseJWT(token);
            userid = (String) claims.get(Constant.userId);
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }

        // 查询redis信息
        String redisKey = Constant.redisKeyPre + userid;
        LoginUser loginUser = (LoginUser) redisTemplate.opsForValue().get(redisKey);
        if (Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录");
        }

        // 存入SecurityContextHolder
        //TODO 获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        // 放行
        filterChain.doFilter(request, response);


    }
}

2.2.3 从数据库查询权限信息
2.3.1 RBAC权限模型

RBAC权限模型(Role-Based Access Control)即:基于角色的权限控制

准备工作 生成数据库文件

注意:下方的sys_user表没有用到 可替换成系统本身的user表

CREATE DATABASE /*!32312 IF NOT EXISTS*/`sg_security` /*!40100 DEFAULT CHARACTER
SET utf8mb4 */;
USE `sg_security`;
/*Table structure for table `sys_menu` */
DROP TABLE IF EXISTS `sys_menu`;
CREATE TABLE `sys_menu` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`menu_name` varchar(64) NOT NULL DEFAULT 'NULL' COMMENT '菜单名',
`path` varchar(200) DEFAULT NULL COMMENT '路由地址',
`component` varchar(255) DEFAULT NULL COMMENT '组件路径',
`visible` char(1) DEFAULT '0' COMMENT '菜单状态(0显示 1隐藏)',
`status` char(1) DEFAULT '0' COMMENT '菜单状态(0正常 1停用)',
`perms` varchar(100) DEFAULT NULL COMMENT '权限标识',
`icon` varchar(100) DEFAULT '#' COMMENT '菜单图标',
`create_by` bigint(20) DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
`update_by` bigint(20) DEFAULT NULL,
`update_time` datetime DEFAULT NULL,
`del_flag` int(11) DEFAULT '0' COMMENT '是否删除(0未删除 1已删除)',
`remark` varchar(500) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COMMENT='菜单表';
/*Table structure for table `sys_role` */
DROP TABLE IF EXISTS `sys_role`;
CREATE TABLE `sys_role` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(128) DEFAULT NULL,
`role_key` varchar(100) DEFAULT NULL COMMENT '角色权限字符串',
`status` char(1) DEFAULT '0' COMMENT '角色状态(0正常 1停用)',
`del_flag` int(1) DEFAULT '0' COMMENT 'del_flag',
`create_by` bigint(200) DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
`update_by` bigint(200) DEFAULT NULL,
`update_time` datetime DEFAULT NULL,
`remark` varchar(500) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COMMENT='角色表';
/*Table structure for table `sys_role_menu` */
DROP TABLE IF EXISTS `sys_role_menu`;
CREATE TABLE `sys_role_menu` (
`role_id` bigint(200) NOT NULL AUTO_INCREMENT COMMENT '角色ID',
`menu_id` bigint(200) NOT NULL DEFAULT '0' COMMENT '菜单id',
PRIMARY KEY (`role_id`,`menu_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;
/*Table structure for table `sys_user` */
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
`user_name` varchar(64) NOT NULL DEFAULT 'NULL' COMMENT '用户名',
`nick_name` varchar(64) NOT NULL DEFAULT 'NULL' COMMENT '昵称',
`password` varchar(64) NOT NULL DEFAULT 'NULL' COMMENT '密码',
`status` char(1) DEFAULT '0' COMMENT '账号状态(0正常 1停用)',
`email` varchar(64) DEFAULT NULL COMMENT '邮箱',
`phonenumber` varchar(32) DEFAULT NULL COMMENT '手机号',
`sex` char(1) DEFAULT NULL COMMENT '用户性别(0男,1女,2未知)',
`avatar` varchar(128) DEFAULT NULL COMMENT '头像',
`user_type` char(1) NOT NULL DEFAULT '1' COMMENT '用户类型(0管理员,1普通用户)',
`create_by` bigint(20) DEFAULT NULL COMMENT '创建人的用户id',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_by` bigint(20) DEFAULT NULL COMMENT '更新人',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
`del_flag` int(11) DEFAULT '0' COMMENT '删除标志(0代表未删除,1代表已删除)',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COMMENT='用户表';
/*Table structure for table `sys_user_role` */
DROP TABLE IF EXISTS `sys_user_role`;
CREATE TABLE `sys_user_role` (
`user_id` bigint(200) NOT NULL AUTO_INCREMENT COMMENT '用户id',
`role_id` bigint(200) NOT NULL DEFAULT '0' COMMENT '角色id',
PRIMARY KEY (`user_id`,`role_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
查询用户权限
SELECT
DISTINCT m.`perms`
FROM
sys_user_role ur
LEFT JOIN `sys_role` r ON ur.`role_id` = r.`id`
LEFT JOIN `sys_role_menu` rm ON ur.`role_id` = rm.`role_id`
LEFT JOIN `sys_menu` m ON m.`id` = rm.`menu_id`
WHERE
user_id = 2
AND r.`status` = 0
AND m.`status` = 0
2.3.2 实现步骤
  1. 将用户权限对应的关系表插入数据库中

  2. 书写对应的Menu实体类(即菜单表,内含用户权限字段)

  3. 书写对应的Mapper查询文件,多表关联查询用户权限

  4. 将查到的用户权限封装到实体类中(上文中实体类已经对该权限进行了处理,利用有参构造即可封装)

  5. 在token过滤器中封装对应权限(上文已经封装)

Menu实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Menu implements Serializable {
    private static final long serialVersionUID = -54979041104113736L;

    private Long id;
    /**
     * 菜单名
     */
    private String menuName;
    /**
     * 路由地址
     */
    private String path;
/**
 * 组件路径
 */
//3.2.3.3 代码实现
//    我们只需要根据用户id去查询到其所对应的权限信息即可。
//    所以我们可以先定义个mapper,其中提供一个方法可以根据userid查询权限信息。
//    尤其是自定义方法,所以需要创建对应的mapper文件,定义对应的sql语句
    private String component;
    /**
     * 菜单状态(0显示 1隐藏)
     */
    private String visible;
    /**
     * 菜单状态(0正常 1停用)
     */
    private String status;
    /**
     * 权限标识
     */
    private String perms;
    /**
     * 菜单图标
     */
    private String icon;
    private Long createBy;
    private Date createTime;
    private Long updateBy;
    private Date updateTime;
    /**
     * 是否删除(0未删除 1已删除)
     */
    private Integer delFlag;
    /**
     * 备注
     */
    private String remark;
}
书写mapper文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.spring.Mapper.MenuMapper">

    <select id="selectPermsByUserId" resultType="java.lang.String">
        SELECT
        DISTINCT m.`perms`
        FROM
        sys_user_role ur
        LEFT JOIN `sys_role` r ON ur.`role_id` = r.`id`
        LEFT JOIN `sys_role_menu` rm ON ur.`role_id` = rm.`role_id`
        LEFT JOIN `sys_menu` m ON m.`id` = rm.`menu_id`
        WHERE
        user_id = #{userid}
        AND r.`status` = 0
        AND m.`status` = 0
    </select>
</mapper>
修改自定义验证功能,查询数据进行封装
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private EmpMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        Emp emp = userMapper.selectUser(username);
        if (Objects.isNull(emp)){
            throw new RuntimeException("用户名或密码错误");
        }

        // TODO 查询用户的授权信息
//        List<String> list = new ArrayList<>(Arrays.asList("system:depts:list"));
        List<String> list = menuMapper.selectPermsByUserId(emp.getId());
        log.info("这里是查询的权限:" + list.toString());
        // LoginUser是继承UserDetails的实体类 封装自定义返回对象
        return new LoginUser(emp, list);
    }
}

3、自定义失败处理器

我们还希望在认证失败或者是授权失败的情况下也能和我们的接口一样返回相同结构的json,这样可以 让前端能对响应进行统一的处理。要实现这个功能我们需要知道SpringSecurity的异常处理机制。

在SpringSecurity中,如果我们在认证或者授权的过程中出现了异常会被ExceptionTranslationFilter捕 获到。在ExceptionTranslationFilter中会去判断是认证失败还是授权失败出现的异常。

如果是认证过程中出现的异常会被封装成AuthenticationException然后调用 AuthenticationEntryPoint对象的方法去进行异常处理。

如果是授权过程中出现的异常会被封装成AccessDeniedException然后调用AccessDeniedHandler对 象的方法去进行异常处理。

所以如果我们需要自定义异常处理,我们只需要自定义AuthenticationEntryPoint和 AccessDeniedHandler然后配置给SpringSecurity即可。

3、1 实现认证失败处理器
  1. 实现AuthenticationEntryPoint接口

  2. 在配置类中添加其实现类

实现AuthenticationEntryPoint接口
@Component
@Slf4j
public class AuthenticationEx implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        // 封装对象
        Result result = Result.error("登录认证失败");
        // 转换为json数据
        String jsonResult = JSONObject.toJSONString(result);
        // 设置返回格式
        response.setContentType("application/json; charset=utf-8");
        // 调用response方法返回
        response.getWriter().print(jsonResult);
        log.info("自定义认证失败");
    }
}
在配置类中添加其实现类
    @Autowired
    private AuthenticationEx authenticationEx;

// 添加自定义认证失败处理器及自定义权限失败处理器
        http.exceptionHandling()
                .authenticationEntryPoint(authenticationEx);
3、2 实现授权失败处理器
  1. 实现AccessDeniedHandler接口

  2. 在配置类中添加其实现类

实现AccessDeniedHandler接口
/**
 * 自定义权限认证失败处理
 */
@Component
@Slf4j
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        // 封装失败返回对象
        Result result = Result.error("您没有该权限");
        // 转换json格式
        String jsonResult = JSONObject.toJSONString(result);
        // 设置返回格式
        response.setContentType("application/json; charset=utf-8");
        // 调用返回对象
        response.getWriter().print(jsonResult);
    }
}
在配置类中添加实现类
    @Autowired
    private AccessDeniedHandlerImpl accessDeniedHandler;

// 添加自定义权限失败处理器
        http.exceptionHandling()
                .accessDeniedHandler(accessDeniedHandler);

完整的配置类
@Configuration
//@EnableWebSecurity  // 代替继承WebSecurityConfigurerAdapter
@EnableGlobalMethodSecurity(prePostEnabled = true)  // 使用该注解开启WebSecurityConfigurerAdapter
public class securityConfig  extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Autowired
    private AuthenticationEx authenticationEx;

    @Autowired
    private AccessDeniedHandlerImpl accessDeniedHandler;

    // 创建BCryptPasswordEncoder注入容器 代替原有的密码加密方式
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    // 对用户的未授信凭据进行认证,认证通过则返回授信状态的凭据,否则将抛出认证异常AuthenticationException
    public AuthenticationManager authenticationManagerBean() throws Exception{
        return super.authenticationManagerBean();
    }

//    配置 HttpSecurity 。 HttpSecurity 用于构建一个安全过滤器链 SecurityFilterChain
//    SecurityFilterChain 最终被注入核心过滤器
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            //关闭csrf
            .csrf().disable()
            //不通过Session获取SecurityContext
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            // 对于登录接口 允许匿名访问
            .antMatchers("/login").anonymous()
            // 除上面外的所有请求全部需要鉴权认证
            .anyRequest().authenticated();

        // 添加token校验的过滤器到过滤器链中
        http.addFilterBefore(jwtAuthenticationTokenFilter,
                UsernamePasswordAuthenticationFilter.class);

        // 添加自定义认证失败处理器及自定义权限失败处理器
        http.exceptionHandling()
                .authenticationEntryPoint(authenticationEx)
                .accessDeniedHandler(accessDeniedHandler);
                
        // 允许跨域
        http.cors();
                
    }
}

跨域

①先对SpringBoot配置,运行跨域请求
@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //添加映射路径
        registry.addMapping("/**")
                //是否发送Cookie
                .allowCredentials(true)
                //设置放行哪些原始域   SpringBoot2.4.4下低版本使用.allowedOrigins("*")
                .allowedOrigins("*")
                //放行哪些请求方式
//                .allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"})
                .allowedMethods("*") //或者放行全部
                //放行哪些原始请求头部信息
                .allowedHeaders("*")
                //暴露哪些原始请求头部信息
                .exposedHeaders("*");
    }
}
②开启SpringSecurity的跨域访问

由于我们的资源都会收到SpringSecurity的保护,所以想要跨域访问还要让SpringSecurity运行跨域访问。在springsecurity的配置类中添加http.cors(); 完整配置类同上

//允许跨域
http.cors();

其他权限认证方法

我们前面都是使用@PreAuthorize注解,然后在在其中使用的是hasAuthority方法进行校验。 SpringSecurity还为我们提供了其它方法例如:hasAnyAuthority,hasRole,hasAnyRole等。

hasAuthority方法实际是执行到了SecurityExpressionRoot的hasAuthority。 它内部其实是调用authentication的getAuthorities方法获取用户的权限列表。然后判断我们存入的方法 参数数据在权限列表中。

hasAnyAuthority方法可以传入多个权限,只有用户有其中任意一个权限都可以访问对应资源。

@PreAuthorize("hasAnyAuthority('admin','test','system:dept:list')")
public String hello(){
return "hello";
}

hasRole要求有对应的角色才可以访问,但是它内部会把我们传入的参数拼接上 ROLE_ 后再去比较。所 以这种情况下要用用户对应的权限也要有 ROLE_ 这个前缀才可以。

@PreAuthorize("hasRole('system:dept:list')")
public String hello(){
return "hello";
}

hasAnyRole 有任意的角色就可以访问。它内部也会把我们传入的参数拼接上 ROLE_ 后再去比较。所以 这种情况下要用用户对应的权限也要有 ROLE_ 这个前缀才可以。

@PreAuthorize("hasAnyRole('admin','system:dept:list')")
public String hello(){
return "hello";
}

自定义权限校验方法

  1. 创建自定义的权限校验类及方法

  2. 在@PreAuthorize注解中调用其方法

书写自定义认证方法
/**
 * 自定义权限校验
 */
@Component("ex")
@Slf4j
public class AuthorityCustomize {
    public boolean hasAuthority(String authority){
        // 获取当前用户权限
        Authentication authentication =
                SecurityContextHolder.getContext().getAuthentication();
        // 转换实体类
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        List<String> permissions = loginUser.getPermissions();
        log.info("我是自定义权限认证");
        // 判断用户权限集合是否存在authority
        return permissions.contains(authority);

    }
}
在@PreAuthorize注解中调用其方法

在SPEL表达式中使用 @ex相当于获取容器中bean的名字为ex的对象。然后再调用这个对象的 hasAuthority方法

    @GetMapping("/depts")
    //    @PreAuthorize("hasAnyAuthority()") 为开启权限访问的注解
//    @PreAuthorize("hasAnyAuthority('system:depts:list')")
    @PreAuthorize("@ex.hasAuthority('system:depts:list')")
    public Result list(){
        log.info("查询到所有部门");
        List<Dept> deptList = deptService.list();
        return Result.success(deptList);
    }

基于配置的权限控制

我们也可以在配置类中使用使用配置的方式对资源进行权限控制。

  @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            //关闭csrf
            .csrf().disable()
            //不通过Session获取SecurityContext
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            // 对于登录接口 允许匿名访问
            .antMatchers("/login").anonymous()
            // 配置接口的访问权限
            .antMatchers("/emp").hasAuthority("system:emp:list")
            // 除上面外的所有请求全部需要鉴权认证
            .anyRequest().authenticated();

        // 添加token校验的过滤器到过滤器链中
        http.addFilterBefore(jwtAuthenticationTokenFilter,
                UsernamePasswordAuthenticationFilter.class);

        // 添加自定义认证失败处理器及自定义权限失败处理器
        http.exceptionHandling()
                .authenticationEntryPoint(authenticationEx)
                .accessDeniedHandler(accessDeniedHandler);

        // 允许跨域
        http.cors();

    }

CSRF

CSRF是指跨站请求伪造(Cross-site request forgery),是web常见的攻击之一。

CSRF攻击与防御(写得非常好)_注销账号可以防范csrf吗-CSDN博客

SpringSecurity去防止CSRF攻击的方式就是通过csrf_token。后端会生成一个csrf_token,前端发起请 求的时候需要携带这个csrf_token,后端会有过滤器进行校验,如果没有携带或者是伪造的就不允许访 问。

我们可以发现CSRF攻击依靠的是cookie中所携带的认证信息。但是在前后端分离的项目中我们的认证信 息其实是token,而token并不是存储中cookie中,并且需要前端代码去把token设置到请求头中才可 以,所以CSRF攻击也就不用担心了。

因为本项目采用的认证方式也是token,所以不用担心csrf的攻击,故此在上述配置类中选择了关闭csrf的功能。

认证成功处理器

默认认证表单消失小细节

在简单案例中我们只需引入springsecurity的依赖就可以开启springsecurity的默认表单认证,而当我们的负责案例配置时表单和usernamepassswordFilter其实是以及消失了,原因是在下面的源码中我们可以看见configure是有默认的表单处理的,而当我们去实现security的配置类时我们会继承WebSecurityConfigurerAdapter类重写其configure方法时并没有处理默认表单,所以默认的表单处理和usernamepassswordFilter其实是已经消失了。

实际上在UsernamePasswordAuthenticationFilter进行登录认证的时候,如果登录成功了是会调用 AuthenticationSuccessHandler的方法进行认证成功后的处理的。AuthenticationSuccessHandler就是 登录成功处理器。 我们也可以自己去自定义成功处理器进行成功后的相应处理。

@Component
public class SGSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication) throws IOException,
ServletException {
System.out.println("认证成功了");
}
}
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationSuccessHandler successHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin().successHandler(successHandler);
http.authorizeRequests().anyRequest().authenticated();
}
}

认证失败处理器

实际上在UsernamePasswordAuthenticationFilter进行登录认证的时候,如果认证失败了是会调用 AuthenticationFailureHandler的方法进行认证失败后的处理的。AuthenticationFailureHandler就是登 录失败处理器。 我们也可以自己去自定义失败处理器进行失败后的相应处理。

@Component
public class SGFailureHandler implements AuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request,
HttpServletResponse response, AuthenticationException exception) throws
IOException, ServletException {
System.out.println("认证失败了");
}
}
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationSuccessHandler successHandler;
@Autowired
private AuthenticationFailureHandler failureHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
// 配置认证成功处理器
.successHandler(successHandler)
// 配置认证失败处理器
.failureHandler(failureHandler);
http.authorizeRequests().anyRequest().authenticated();
}
}

登出成功处理器

@Component
public class SGLogoutSuccessHandler implements LogoutSuccessHandler {
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse
response, Authentication authentication) throws IOException, ServletException {
System.out.println("注销成功");
}
}
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationSuccessHandler successHandler;
@Autowired
private AuthenticationFailureHandler failureHandler;
@Autowired
private LogoutSuccessHandler logoutSuccessHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
// 配置认证成功处理器
.successHandler(successHandler)
// 配置认证失败处理器
.failureHandler(failureHandler);
http.logout()
//配置注销成功处理器
.logoutSuccessHandler(logoutSuccessHandler);
http.authorizeRequests().anyRequest().authenticated();
}
}
  • 10
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Security是一个用于在Java应用程序中实现身份验证和授权的框架。它提供了一种可靠和灵活的方法来管理应用程序中的权限。通过使用Spring Security,可以轻松地自定义登录授权过程。 首先,我们需要创建一个实现`UserDetailsService`接口的类来处理用户的身份验证。在这个类中,我们可以自定义用户的登录逻辑,例如验证用户名和密码。我们可以使用Spring Security提供的各种验证方法来验证用户的身份。 接下来,我们需要配置Spring Security来处理用户的授权。可以使用`WebSecurityConfigurerAdapter`类扩展一个配置类,并覆盖其中的`configure`方法。在这个方法中,我们可以指定哪些URL需要受到保护,哪些URL可以公开访问。例如,我们可以使用`antMatchers`方法来指定URL模式,然后使用`hasAuthority`或`hasRole`方法来指定用户需要具备的权限或角色。 另外,我们还可以使用`@PreAuthorize`注解来在方法级别上进行授权。可以在需要进行授权的方法上添加该注解,并指定用户需要具备的权限或角色。 最后,我们还可以通过自定义`AuthenticationProvider`来实现更复杂的授权逻辑。可以创建一个实现该接口的类,并在其中实现自定义的身份验证和授权逻辑。然后可以将这个自定义的`AuthenticationProvider`添加到Spring Security的配置中。 通过以上的方法,我们可以灵活地自定义登录授权过程Spring Security提供了丰富的配置选项和接口来满足各种不同的授权需求。使用Spring Security,我们可以有效地管理应用程序中的权限,并确保只有具备合适权限的用户可以访问受保护的资源。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值