SpringSecurity设置登录用户(连接数据库)

1:设置登录系统的账号,密码

如果没有配置登录的用户则会默认配置用户名为user且密码为控制台输出。

配置的前提:配置类中注入PasswordEncoder 的实现类对象

 //设置登录的账号密码需要配置密码解析器
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

方式1:yaml配置

spring:
  security:
    user:
      name: test
      password: test

方式2:编写类实现接口

//使用service注解命名为test 需要实现UserDetailsService接口
@Service("test")
public class LoginService implements UserDetailsService {
    //重写loadUserByUsername
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //密码
        String pwd=null;
        //用户权限集合
        List<GrantedAuthority> authorityList=null;
        //密码解析器
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        try{
            if(username.equals("test")){
                //密码需要以加密方式传递
                pwd=bCryptPasswordEncoder.encode("test");
                //为此用户设置权限为test ROLE_为前缀
                authorityList=AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_test");
                //返回User对象此User为SpringSecurity自带的实现UserDetails接口的类
                //用户名,加密参数。用户权限集合
                return new User(username, pwd, authorityList);
            }
        }catch (UsernameNotFoundException e){//需要抛出用户不存在的异常
            System.out.println("用户不存在");
        }
        return null;
    }
}

在配置文件中配置UserDetailsService的实现类:

@Configuration//配置类,继承WebSecurityConfigurerAdapter
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //将test的LoginService注入
    @Autowired
    UserDetailsService test;

    //重写configure(HttpSecurity http)方法
    @Override
    protected void configure(HttpSecurity http) throws Exception {
                 //登录
            http.formLogin()
                .and()
                .authorizeRequests()
                    //test权限才可以访问/test路径
                    .antMatchers("/test").hasRole("test")
                    //配置一个test权限不可以访问的路径
                    .antMatchers("/notTest").hasRole("notTest")
                    //所有人都可以访问/路径
                    .antMatchers("/").permitAll()
                    //任何请求都需要认证
                    .anyRequest().authenticated();
    }

    //设置登录的账号密码需要配置密码解析器
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

如果权限不够则会报403错误

2:实现数据库认证

1:创建数据表

在这里插入图片描述
依赖:

        <!--mysql-->
		<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.37</version>
        </dependency>
		<!--数据库连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.17</version>
        </dependency>
		<!--mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>

yaml配置:

spring:
  datasource:
    password: 
    username: 
    url: 
    type: com.alibaba.druid.pool.DruidDataSource

配置后使用IDEA连接数据库,使用MyBatisX插件快速生成模板代码(详情连接)

2:自定义UserDetailsService

@Service("DBLoginService")
public class DBLoginService implements UserDetailsService {

    @Autowired
    private  UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //使用mybatis-plus的条件构造器通过用户名查询用户
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        //user_name字段等于username
        queryWrapper.eq("user_name", username);
        User user = userMapper.selectOne(queryWrapper);

        //不存在抛出异常
        if(user==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        //设置用户权限
        List<GrantedAuthority> authorityList= AuthorityUtils.commaSeparatedStringToAuthorityList("dbUser");
        //返回的对象还是SpringSecurity的User对象
        return new org.springframework.security.core.userdetails.User(username, new BCryptPasswordEncoder().encode(user.getPassword()),authorityList);

    }
}

使用MyBatisPlus的条件构造器(使用详情)

3:在Security配置文件中配置

Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //注入UserDetailsService
    @Autowired
    private UserDetailsService DBLoginService;

    //注入密码解析器
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.formLogin()
                .and()
                //配置权限
                .authorizeRequests()
                //权限为dbUser的用户可以访问/dbUser路径
                .antMatchers("/dbUser").hasAuthority("dbUser")
                //  /路径所有人都可以访问 未登录也可以访问
                .antMatchers("/").permitAll()
                //任何的请求都需要认证
                .anyRequest().authenticated();

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值