• 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);
    }
  • 相关阅读:
    只要7步,就能将任何魔方6面还原
    写一篇文章测试一下
    关于80端口被占用
    打造只能输入数字的文本框
    windows下MySql忘记密码的解决方案
    linq to xml 操作sitemap
    C#设计模式——工厂方法模式(Factory Method Pattern)
    C#设计模式——单件模式(Singleton Pattern)
    C#设计模式——迭代器模式(Iterator Pattern)
    C#设计模式——状态模式(State Pattern)
  • 原文地址:https://www.cnblogs.com/xp0813/p/12779477.html
Copyright © 2020-2023  润新知