当前位置:   article > 正文

springBoot整合springSecurity(认证)_springbootsecurity登录认证

springbootsecurity登录认证

springSecurity(安全)

1.什么是springSecurity?

Spring Security是 Spring 家族中的一个安全管理框架。相比与另外一个安全框架Shiro,它提供了更丰富的功能,社区资源也比Shiro丰富;

Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架。它是用于保护基于Spring的应用程序的实际标准;

Spring Security是一个框架,致力于为Java应用程序提供身份验证和授权。与所有Spring项目一样,Spring Security的真正强大之处在于可以轻松扩展以满足自定义要求。

在 Java 生态中,目前有 Spring Security 和 Apache Shiro 两个安全框架,可以完成认证和授权的功能。

我们先来学习下 Spring Security 。其官方对自己介绍如下:

Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications.

Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架。它是保护基于Spring的应用程序的事实标准。

Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to meet custom requirementsSpring

Security是一个专注于为Java应用程序提供身份验证和授权的框架。与所有Spring项目一样,Spring Security的真正威力在于它可以多么容易地扩展以满足定制需求

一般Web应用的需要进行认证和授权。

认证(Authentication):验证当前访问系统的是不是本系统的用户,并且要确认具体是哪个用户

授权(Authorization):经过认证后判断当前用户是否有权限进行某个操作

而认证和授权就是SpringSecurity作为安全框架的核心功能。

2.认证

2.1导入springSecurity依赖

  1. <dependency>
  2.    <groupId>org.springframework.boot</groupId>
  3.    <artifactId>spring-boot-starter-security</artifactId>
  4. </dependency>

然后运行项目

输入localhost:自己的端口号会出来这个页面

img

此时所有的接口都已经被保护了

2.2那账号密码是什么呢

我们查看一下控制台

img

有一串uuid这就是密码,账号为user

输入进去就可以登录成功了

img

2.3表单登录

2.3.1登录的html文件

在resources里面的static目录创建一个html文件

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.    <meta charset="UTF-8">
  5.    <title>登陆</title>
  6.    <link
  7.            href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"
  8.            rel="stylesheet" id="bootstrap-css">
  9.    <script
  10.            src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" >
  11.    </script>
  12.    <script
  13.            src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js">
  14.    </script>
  15. </head>
  16. <style>
  17.    #login .container #login-row #login-column #login-box{
  18.        border: 1px solid #9c9c9c ;
  19.        background-color: #EAEAEA;
  20.   }
  21. </style>
  22. <body>
  23. <form id="login-form" class="form" action="/doLogin" method="post">
  24.    <h3>登录</h3>
  25.    <label for="username" class="text-into" >用户名</label><br>
  26.    <input type="text" name="uname" id="username" class="form-control" ><br>
  27.    <label for="password" class="text-info">密码</label><br>
  28.    <input type="password" name="passwd" id="password" class="form-control"><br>
  29.    <input type="submit" name="submit" class="btn btn-info btn-md" value="登录">
  30. </form>
  31. </body>
  32. </html>

2.3.2配置一下security的配置

创建一个SecurityConfig配置类

继承WebSecurityConfigurerAdapter

  1. @Configuration
  2. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  3.    @Autowired
  4.    private UserDetailsServiceImpl userDetailsService;
  5.    @Override
  6.    protected void configure(HttpSecurity http) throws Exception {
  7.        //authorizeRequests开启权限配置
  8.        http.authorizeRequests()
  9.                //anyRequest().authenticated()所有请求都要认证
  10.               .anyRequest().authenticated()
  11.                //and()和http.同意
  12.               .and()
  13.                //formLogin开启表单登陆的配置
  14.               .formLogin()
  15.                //loginPage登录的页面地址
  16.               .loginPage("/mylogin.html")
  17.                //loginProcessingUrl登录接口
  18.               .loginProcessingUrl("/doLogin")
  19. //               //defaultSuccessUrl登录成功跳转的页面,如果直接到Login页面登陆成功跳转的地址
  20.               .defaultSuccessUrl("/index")
  21.                //登陆失败跳转的路径,并且携带错误信息
  22.               .failureForwardUrl("/mylogin.html")
  23.                //登录的用户名
  24.               .usernameParameter("uname")
  25.                //登录的密码
  26.               .passwordParameter("passwd")
  27.                //表示跟登录相关的接口不拦截
  28.               .permitAll()
  29.               .and()
  30.                //关闭csrf跨域攻击
  31.               .csrf().disable();
  32.   }
  33. }

2.3.3设置登录的账号密码

在application.yml文件当中配置

  1. spring:
  2.  #security
  3. security:
  4.   user:
  5.     name: admin
  6.     password: 123456

登录成功之后会跳转到/index接口

登录失败之后会再次跳转到/mylogin.html的登录页面

2.3.4前后分离之下的登录

有时候页面跳转并不能满足我们的需求,特别是现在流行的前后分离开发当中,用户登录成功后就不需要跳转了,

只需要返回给前端一个JSON数据即可,告诉前端登录成功还是登录失败,全端接收到消息之后自行处理。

像这样的需求,我们可以通过自定义的AuthenticationHandler

2.3.4.1登录成功处理器

  1. @Configuration
  2. public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
  3.    //自定义配置登录成功的处理器
  4.    @Override
  5.    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
  6.        response.setContentType("application/json;charset=utf-8");
  7.        Map<String,Object> successMap=new HashMap<>();
  8.        successMap.put("msg","登录成功");
  9.        successMap.put("code",200);
  10.        ObjectMapper objectMapper=new ObjectMapper();
  11.        String successLogin=objectMapper.writeValueAsString(successMap);
  12.        response.getWriter().write(successLogin);
  13.   }
  14. }

2.3.4.2登录失败处理器

  1. @Configuration
  2. public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
  3.    //自定义配置登录失败返回的信息
  4.    @Override
  5.    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
  6.        response.setContentType("application/json;charset=utf-8");
  7.        Map<String,Object> successMap=new HashMap<>();
  8.        successMap.put("msg","登录失败"+exception.getMessage());
  9.        successMap.put("code", Constants.CODE_500);
  10.        ObjectMapper objectMapper=new ObjectMapper();
  11.        String successLogin=objectMapper.writeValueAsString(successMap);
  12.        response.getWriter().write(successLogin);
  13.   }
  14.    
  15. }

2.3.4.3重新配置一下

修改一下刚才的SpringSecurity配置

  1. @Configuration
  2. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  3.    @Autowired
  4.    private UserDetailsServiceImpl userDetailsService;
  5.    @Override
  6.    protected void configure(HttpSecurity http) throws Exception {
  7.        //authorizeRequests开启权限配置
  8.        http.authorizeRequests()
  9.                //anyRequest().authenticated()所有请求都要认证
  10.               .anyRequest().authenticated()
  11.                //and()和http.同意
  12.               .and()
  13.                //formLogin开启表单登陆的配置
  14.               .formLogin()
  15.                //loginPage登录的页面地址
  16.               .loginPage("/mylogin.html")
  17.                //loginProcessingUrl登录接口
  18.               .loginProcessingUrl("/doLogin")
  19.                 //自定义登录成功的处理器
  20.               .successHandler(new MyAuthenticationSuccessHandler())
  21.                //自定义登陆失败的处理器
  22.               .failureHandler(new MyAuthenticationFailureHandler())
  23.                //登录的用户名
  24.               .usernameParameter("uname")
  25.                //登录的密码
  26.               .passwordParameter("passwd")
  27.                //表示跟登录相关的接口不拦截
  28.               .permitAll()
  29.               .and()
  30.                //关闭csrf跨域攻击
  31.               .csrf().disable();
  32.   }
  33. }

再次重启

2.3.4.4登录成功返回的信息

img

2.3.4.5登录失败返回的信息

img

2.4退出登录

2.4.1默认的退出登录

添加退出登录的security配置

  1. @Configuration
  2. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  3. @Override
  4. protected void configure(HttpSecurity http) throws Exception {
  5. //authorizeRequests开启权限配置
  6. http.authorizeRequests()
  7. //anyRequest().authenticated()所有请求都要认证
  8. .anyRequest().authenticated()
  9. //and()和http.同意
  10. .and()
  11. //formLogin开启表单登陆的配置
  12. .formLogin()
  13. //loginPage登录的页面地址
  14. .loginPage("/mylogin.html")
  15. //loginProcessingUrl登录接口
  16. .loginProcessingUrl("/doLogin")
  17. //自定义登录成功的处理器
  18. .successHandler(new MyAuthenticationSuccessHandler())
  19. //自定义登陆失败的处理器
  20. .failureHandler(new MyAuthenticationFailureHandler())
  21. //登录的用户名
  22. .usernameParameter("uname")
  23. //登录的密码
  24. .passwordParameter("passwd")
  25. //表示跟登录相关的接口不拦截
  26. .permitAll()
  27. .and()
  28. //logout开启注销配置
  29. .logout()
  30. //logoutUrl注销登录的请求路径
  31. .logoutUrl("/logout")
  32. .invalidateHttpSession(true)
  33. //clearAuthentication表示清除认证信息,默认为true
  34. .clearAuthentication(true)
  35. //logoutSuccessUrl退出成功之后的页面
  36. .logoutSuccessUrl("/mylogin.html")
  37. //关闭csrf跨域攻击
  38. .csrf().disable();
  39. }
  40. }

security的默认的退出路径为logout,退出成功返回的页面为/mylogin.html

2.4.2退出登录的处理器

退出登录也可以和登录成功登录失败一样,返回json数据

  1. @Configuration
  2. public class MyLogoutSuccessHandler implements LogoutSuccessHandler {
  3.    @Override
  4.    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
  5.        response.setContentType("application/json;charset=utf-8");
  6.        Map<String,Object> successMap=new HashMap<>();
  7.        successMap.put("msg","退出成功");
  8.        successMap.put("code",200);
  9.        ObjectMapper objectMapper=new ObjectMapper();
  10.        String successLogin=objectMapper.writeValueAsString(successMap);
  11.        response.getWriter().write(successLogin);
  12.   }
  13. }

同时也要配置一下

  1. @Configuration
  2. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  3. @Autowired
  4. private UserDetailsServiceImpl userDetailsService;
  5. @Override
  6. protected void configure(HttpSecurity http) throws Exception {
  7.   //authorizeRequests开启权限配置
  8.   http.authorizeRequests()
  9.           //anyRequest().authenticated()所有请求都要认证
  10.           .anyRequest().authenticated()
  11.           //and()和http.同意
  12.           .and()
  13.           //formLogin开启表单登陆的配置
  14.           .formLogin()
  15.           //loginPage登录的页面地址
  16.           .loginPage("/mylogin.html")
  17.           //loginProcessingUrl登录接口
  18.           .loginProcessingUrl("/doLogin")
  19.             //自定义登录成功的处理器
  20.           .successHandler(new MyAuthenticationSuccessHandler())
  21.           //自定义登陆失败的处理器
  22.           .failureHandler(new MyAuthenticationFailureHandler())
  23.           //登录的用户名
  24.           .usernameParameter("uname")
  25.           //登录的密码
  26.           .passwordParameter("passwd")
  27.           //表示跟登录相关的接口不拦截
  28.           .permitAll()
  29.           .and()
  30.           //logout开启注销配置
  31.           .logout()
  32.           //logoutUrl注销登录的请求路径
  33.           .logoutUrl("/logout")
  34.           //配置退出登录处理器
  35.           .logoutSuccessHandler(new MyLogoutSuccessHandler())
  36.           .invalidateHttpSession(true)
  37.           //clearAuthentication表示清除认证信息,默认为true
  38.           .clearAuthentication(true)
  39.           //关闭csrf跨域攻击
  40.           .csrf().disable();
  41. }
  42. }

2.5登录用户数据获取

2.5.1从SecurityContextHolder中获取

登录成功之后直接可以通过security中获取对象信息,security已经给我们封装好了

  1. @GetMapping("/getUser")
  2.    public Object getUserInfo(){
  3.        //获取用户信息
  4.        return SecurityContextHolder.getContext().getAuthentication().getPrincipal();
  5.   }

我们用账号admin登录

img

这样就能获取到用户信息了

是Authentication里面有五个接口

  1. //获取用户权限
  2. Collection<? extends GrantedAuthority> getAuthorities();
  3. //获取用户凭证,一般是密码,但是为了安全返回的是null
  4. Object getCredentials();
  5. //用来获取用户详细信息
  6. Object getDetails();
  7. //获取当前用户信息,可以是一个用户名,也可以是一个用户对象
  8. Object getPrincipal();
  9. //当前用户是否认证成功
  10. boolean isAuthenticated();

2.5.2从当前请求对象中获取

  1. @RequestMapping("/authentication")
  2. public AjaxResult authentication(Authentication authentication){
  3.    return authentication;
  4. }
  5. @RequestMapping("/principal")
  6. public AjaxResult principal(Principal principal){
  7.    return principal;
  8. }

第一个方法返回的用户信息

img

第二个方法获取的用户信息

返回的其实差不多,因为authentication是继承principal的

2.6自定义认证用户信息

2.6.1基于内存

前面的案例都是基于内存的,只是我们没有将InMemoryUserDetailsManager

在刚才的security配置类里面,重写springSecurity认证方式的方法

img

  1. @Override
  2.    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  3.        //基于内存的用户
  4.        InMemoryUserDetailsManager manager=new InMemoryUserDetailsManager();
  5.        //创建用户,设置用户名,密码,角色
  6.        manager.createUser(User.withUsername("admin").password("{noop}123").roles("admin").build());
  7.        manager.createUser(User.withUsername("user").password("{noop}123").roles("user").build());
  8.        //存储到authentication里面
  9.        auth.userDetailsService(manager);
  10.   }

{noop}前缀表示密码不加密

重写这个认证方式,就只能用设置的账号登录了,在实际项目中是不可能的这样配置的,都是用数据库的进行认证的

2.6.1基于Mybatis认证

(我用的是MyBatis-plus意义一样,可自行选择)****

(1)导入mybatis和MySQL-connector的依赖

  1. <dependency>
  2.   <groupId>com.baomidou</groupId>
  3.   <artifactId>mybatis-plus-boot-starter</artifactId>
  4.   <version>3.5.2</version>
  5. </dependency>
  6. <dependency>
  7.   <groupId>mysql</groupId>
  8.   <artifactId>mysql-connector-java</artifactId>
  9.   <scope>runtime</scope>
  10. </dependency>

(2)配置数据库和myBatis

  1. spring:
  2. datasource:
  3.   url: jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8&characterEncoding=utf-8
  4.   username: root
  5.   password: 123888
  6.   driver-class-name: com.mysql.cj.jdbc.Driver

  1. mybatis:
  2. mapper-locations: classpath:mapper/*Mapper.xml
  3.  # ???????
  4. typeAliasesPackage: com.frank.pojo
  5. configuration:
  6. #   #????SQL??
  7.   log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

2.6.2创建数据库表

用户表

  1. /*
  2. Navicat Premium Data Transfer
  3. Source Server         : localhost_3306
  4. Source Server Type   : MySQL
  5. Source Server Version : 80028
  6. Source Host           : localhost:3306
  7. Source Schema         : test
  8. Target Server Type   : MySQL
  9. Target Server Version : 80028
  10. File Encoding         : 65001
  11. Date: 14/10/2022 01:10:29
  12. */
  13. SET NAMES utf8mb4;
  14. SET FOREIGN_KEY_CHECKS = 0;
  15. -- ----------------------------
  16. -- Table structure for user_info
  17. -- ----------------------------
  18. DROP TABLE IF EXISTS `user_info`;
  19. CREATE TABLE `user_info`  (
  20.  `id` int(0) NOT NULL AUTO_INCREMENT COMMENT 'id',
  21.  `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '用户名',
  22.  `password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '密码',
  23.  `create_time` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间',
  24.  `update_time` datetime(0) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '修改时间',
  25.  `deleted` int(0) NULL DEFAULT 0 COMMENT '逻辑删除',
  26.  PRIMARY KEY (`id`) USING BTREE
  27. ) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
  28. -- ----------------------------
  29. -- Records of user_info
  30. -- ----------------------------
  31. INSERT INTO `user_info` VALUES (1, 'user', '{noop}123456', '2022-10-02 10:33:46', '2022-10-12 00:40:19', 0);
  32. INSERT INTO `user_info` VALUES (2, 'admin', '{noop}123456', '2022-10-02 10:33:46', '2022-10-12 00:40:21', 0);
  33. INSERT INTO `user_info` VALUES (3, 'caixvkun', '{noop}123456', '2022-10-02 10:33:46', '2022-10-12 00:40:22', 0);
  34. INSERT INTO `user_info` VALUES (4, 'wujinxiang', '{noop}123456', '2022-10-02 14:09:49', '2022-10-12 00:40:24', 0);
  35. SET FOREIGN_KEY_CHECKS = 1;

角色表

  1. /*
  2. Navicat Premium Data Transfer
  3. Source Server         : localhost_3306
  4. Source Server Type   : MySQL
  5. Source Server Version : 80028
  6. Source Host           : localhost:3306
  7. Source Schema         : test
  8. Target Server Type   : MySQL
  9. Target Server Version : 80028
  10. File Encoding         : 65001
  11. Date: 14/10/2022 01:10:40
  12. */
  13. SET NAMES utf8mb4;
  14. SET FOREIGN_KEY_CHECKS = 0;
  15. -- ----------------------------
  16. -- Table structure for role
  17. -- ----------------------------
  18. DROP TABLE IF EXISTS `role`;
  19. CREATE TABLE `role`  (
  20.  `id` int(0) NOT NULL AUTO_INCREMENT COMMENT 'ID',
  21.  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '角色',
  22.  `nameZh` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '名称',
  23.  `create_time` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间',
  24.  `update_time` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',
  25.  `deleted` int(0) NULL DEFAULT 0 COMMENT '删除标志',
  26.  PRIMARY KEY (`id`) USING BTREE
  27. ) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
  28. -- ----------------------------
  29. -- Records of role
  30. -- ----------------------------
  31. INSERT INTO `role` VALUES (1, 'ROLE_dba', '数据库管理员', '2022-10-02 10:32:06', NULL, 0);
  32. INSERT INTO `role` VALUES (2, 'ROLE_admin', '系统管理员', '2022-10-02 10:32:06', NULL, 0);
  33. INSERT INTO `role` VALUES (3, 'ROLE_user', '用户', '2022-10-02 10:32:06', NULL, 0);
  34. SET FOREIGN_KEY_CHECKS = 1;

(用户关系表和角色表)

  1. Navicat Premium Data Transfer
  2. Source Server         : localhost_3306
  3. Source Server Type    : MySQL
  4. Source Server Version : 80028
  5. Source Host           : localhost:3306
  6. Source Schema         : test
  7. Target Server Type    : MySQL
  8. Target Server Version : 80028
  9. File Encoding         : 65001
  10. Date: 14/10/2022 01:10:48
  11. */
  12. SET NAMES utf8mb4;
  13. SET FOREIGN_KEY_CHECKS = 0;
  14. -- ----------------------------
  15. -- Table structure for user_role
  16. -- ----------------------------
  17. DROP TABLE IF EXISTS `user_role`;
  18. CREATE TABLE `user_role`  (
  19.  `id` int(0) NOT NULL AUTO_INCREMENT COMMENT 'id',
  20.  `uid` int(0) NULL DEFAULT NULL COMMENT '用户id',
  21.  `rid` int(0) NULL DEFAULT NULL COMMENT '角色id',
  22.  PRIMARY KEY (`id`) USING BTREE
  23. ) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
  24. -- ----------------------------
  25. -- Records of user_role
  26. -- ----------------------------
  27. INSERT INTO `user_role` VALUES (1, 2, 1);
  28. INSERT INTO `user_role` VALUES (2, 2, 2);
  29. INSERT INTO `user_role` VALUES (3, 1, 2);
  30. INSERT INTO `user_role` VALUES (4, 3, 3);
  31. INSERT INTO `user_role` VALUES (5, 4, 3);
  32. SET FOREIGN_KEY_CHECKS = 1;

2.6.3创建用户实体类

并且用户实体类继承UserDetails

  1. @Data
  2. public class UserInfo implements UserDetails {
  3.    private Long id;
  4.    private String username;
  5.    private String password;
  6.    @TableField(exist = false)
  7.    private Boolean enabled;
  8.    @TableField(exist = false)
  9.    private Boolean accountNonExpired;
  10.    @TableField(exist = false)
  11.    private Boolean accountNonLocked;
  12.    @TableField(exist = false)
  13.    private Boolean credentialsNonExpired;
  14.    @TableField(exist = false)
  15.    private List<Role> roleList;
  16.    @TableLogic//逻辑删除的注解
  17.    private Integer deleted;
  18. //获取用户的权限
  19.    @Override
  20.    public Collection<? extends GrantedAuthority> getAuthorities() {
  21.        List<SimpleGrantedAuthority> authorities=new ArrayList<>();
  22.        for (Role role : roleList) {
  23.            authorities.add(new SimpleGrantedAuthority(role.getName()));
  24.       }
  25.        return authorities;
  26.   }
  27.    @Override
  28.    public boolean isAccountNonExpired() {
  29.        return accountNonExpired=true;
  30.   }
  31.    @Override
  32.    public boolean isAccountNonLocked() {
  33.        return accountNonLocked=true;
  34.   }
  35.    @Override
  36.    public boolean isCredentialsNonExpired() {
  37.        return credentialsNonExpired=true;
  38.   }
  39.    @Override
  40.    public boolean isEnabled() {
  41.        return enabled=true;
  42.   }
  43.    @Override
  44.    public String getUsername() {
  45.        return username;
  46.   }
  47.    public String getPassword() {
  48.        return password;
  49.   }
  50. }

role权限的实体类

  1. package com.frank.pojo;
  2. import com.baomidou.mybatisplus.annotation.IdType;
  3. import com.baomidou.mybatisplus.annotation.TableId;
  4. import com.baomidou.mybatisplus.annotation.TableLogic;
  5. import lombok.Data;
  6. import java.io.Serializable;
  7. @Data
  8. public class Role implements Serializable {
  9.   @TableId(type = IdType.AUTO)
  10.   private Long id;
  11.   private String name;
  12.   private String nameZh;
  13.   @TableLogic
  14.   private Integer deleted;
  15. }

2.6.4重写UserDetailsService

  1. @Service
  2. public class UserDetailsServiceImpl implements UserDetailsService {
  3.     @Autowired
  4.     private UserMapper userMapper;
  5.     //自定义认证逻辑
  6.     @Override
  7.     public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  8.         QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<>();
  9.         //根据username查询用户是否存在
  10.         queryWrapper.eq("username",username);
  11.         UserInfo userInfo = userMapper.selectOne(queryWrapper);
  12.         //判断用户是否存在,不存在就返回异常
  13.         if (userInfo==null){
  14.             throw new ServiceException(Constants.CODE_500,"用户不存在");
  15.         }else {
  16.             List<Role> roles = userMapper.queryByIdRole(userInfo.getId());
  17.             //用户存在,获取用户的角色,把角色存到用户校色里面
  18.             userInfo.setRoleList(roles);
  19.         }
  20.         return userInfo;
  21.     }
  22. }

userMapper.queryByIdRole(userInfo.getId());

  1. @Mapper
  2. public interface UserMapper extends BaseMapper<UserInfo> {
  3. //根据用户id获取用户的权限
  4.   List<Role> queryByIdRole(Long id);
  5. }

UserMapper.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.frank.mapper.UserMapper">
  6. <select id="queryByIdRole" resultType="com.frank.pojo.Role">
  7. select r.id, r.name, r.nameZh
  8. from role r
  9. INNER JOIN user_role ur
  10. ON ur.rid = r.id
  11. INNER JOIN `user_info` u
  12. ON ur.uid = u.id
  13. where u.id = #{id} and r.deleted=0
  14. </select>
  15. </mapper>

2.6.5 修改security的认证配置

  1. //上面省略
  2. //注入UserDetailsServiceImpl的bean
  3. @Autowired
  4. private UserDetailsServiceImpl userDetailsService;
  5. @Override
  6. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  7. auth.userDetailsService(userDetailsService);
  8. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/53917
推荐阅读
相关标签
  

闽ICP备14008679号