Spring Security 基于权限或角色进行访问控制的四种方法

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin() //自定义自己编写的登录页面
                //.loginPage("/login.html")   //登录页面设置
                //.loginProcessingUrl("/user/login")
                .defaultSuccessUrl("/test/index")    //登录成功后的跳转路径
                .permitAll()
                .and().authorizeRequests()
                .antMatchers("/", "/test/hello", "/user/login").permitAll()
                //1、hasAuthority(),当前登录用户,只有具有admin权限才可以访问这个路径
                //.antMatchers("/test/index").hasAuthority("admin")
                //2、hasAnyAuthority(),多角色匹配
                //.antMatchers("/test/index").hasAnyAuthority("admin", "manager")
                //3、hasRole()
                //.antMatchers("/test/index").hasRole("sale")
                //4、hasAnyRole()
                .antMatchers("/test/index").hasAnyRole("sale")
                .anyRequest().authenticated()
                .and().csrf().disable();
    }
}

@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 调用userMapper方法查询数据库
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        User user = userMapper.selectOne(wrapper);

        // 数据库没有用户名,认证失败
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }

        List<GrantedAuthority> authorityList = AuthorityUtils
                .commaSeparatedStringToAuthorityList("admin,ROLE_sale");
        String s = new BCryptPasswordEncoder().encode(user.getPassword());
        System.out.println(s);
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorityList);
    }
}
上一篇:SpringSecurity权限认证(三)


下一篇:Day46_Spring Security—Spring Security的Web使用(尚硅谷)