• SpringSecurity连接数据库


    一.创建

      需要在之前SpringSecurity的基础上添加数据库依赖

    二.根据数据库创建用户角色类和用户实体类

      角色类

    public class Role {  private Long id;
        private String name;
        private String nameZh;
        //省略 getter/setter
    }

      用户实体类

    public class User implements UserDetails {
        private Long id;
        private String username;
        private String password;
        private boolean accountNonExpired;    //账户是否没有过期
        private boolean accountNonLocked;     //账号是否没有被锁
        private boolean credentialsNonExpired;   //密码是否没有过期
        private boolean enabled;                //账号是否可用
        @ManyToMany(fetch = FetchType.EAGER,cascade = CascadeType.PERSIST)
        private List<Role> roles;     //User 和 Role 是多对多关系,用一个 @ManyToMany 注解来描述。
        @Override
        public Collection<? extends GrantedAuthority> getAuthorities() {
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            for (Role role : getRoles()) {
                authorities.add(new SimpleGrantedAuthority(role.getName()));
            }
            return authorities;
        }
        @Override
        public String getPassword() {
            return password;
        }
    
        @Override
        public String getUsername() {
            return username;
        }
    
        @Override
        public boolean isAccountNonExpired() {
            return accountNonExpired;
        }
    
        @Override
        public boolean isAccountNonLocked() {
            return accountNonLocked;
        }
    
        @Override
        public boolean isCredentialsNonExpired() {
            return credentialsNonExpired;
        }
    
        @Override
        public boolean isEnabled() {
            return enabled;
        }
        //省略其他 get/set 方法
    }

    三.使用

      

    @Service
    public class SsoUserDetailsService implements UserDetailsService {
    
        @Autowired
        UserMapper userMapper;    //使用mybatis操作数据库
       
        @Override
        public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
           
            User user= userMapper.loadUserByName(name);
            if (user== null) {
                throw new UsernameNotFoundException("用户名不存在!");
            }
            return user;
        }
    }

    四.配置

      1.application.properties 中配置一下数据库

      2.在继承了 WebSecurityConfigurerAdapter类的类中添加如下代码

    @Autowired
    UserService userService;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService);
    }
  • 相关阅读:
    php中strstr、strrchr、substr、stristr四个函数的区别总结
    Python
    PHP Date()函数详细参数
    mysql插入数据时,中文乱码
    mysql中类似indexOf的方法LOCATE()
    获取某个文件夹中所有txt文件
    响应式图片布局
    响应式表格布局
    css媒体类型
    html+css调用服务器端字体
  • 原文地址:https://www.cnblogs.com/xp0813/p/12779477.html
Copyright © 2020-2023  润新知