Spring security中基于权限访问与控制

一、hasAuthority

如果当前的主体具有指定的权限,则返回true,否则返回false

1.在配置类设置权限

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

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


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin() //自定义编写的登录页面
            .loginPage("/login.html")//登录页面设置
            .loginProcessingUrl("/user/login")//登录后访问路径
            .defaultSuccessUrl("/test/index")//登录成功后跳转路径
            .and().authorizeRequests()
                .antMatchers("/","/user/login").permitAll()//设置哪些路径可以直接访问,不需要认证
                .antMatchers("/test/index").hasAuthority("admins")//只有具有admins权限可以访问这个路径
                .anyRequest().authenticated()//除上面外的所有请求全部需要鉴权认证
                .and().csrf().disable();//关闭csrf防护
    }

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

}

2.把返回的User对象设置权限 

@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("admins");
        return new User("tom",new BCryptPasswordEncoder().encode("123456"),auths);
    }
}

 

二、hasAnyAuthority

如果当前主体包含给定的权限列表(逗号分割)则返回true

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin() //自定义编写的登录页面
            .loginPage("/login.html")//登录页面设置
            .loginProcessingUrl("/user/login")//登录后访问路径
            .defaultSuccessUrl("/test/index")//登录成功后跳转路径
            .and().authorizeRequests()
                .antMatchers("/","/user/login").permitAll()//设置哪些路径可以直接访问,不需要认证
                .antMatchers("/test/index").hasAnyAuthority("admins,manager")//具有admins和manager权限可以访问这个路径
                .anyRequest().authenticated()//除上面外的所有请求全部需要鉴权认证
                .and().csrf().disable();//关闭csrf防护
    }

 

@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("admins,manager");
        return new User("tom",new BCryptPasswordEncoder().encode("123456"),auths);
    }
}

三、hasRole

1.在配置类设置角色

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

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


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin() //自定义编写的登录页面
            .loginPage("/login.html")//登录页面设置
            .loginProcessingUrl("/user/login")//登录后访问路径
            .defaultSuccessUrl("/test/index")//登录成功后跳转路径
            .and().authorizeRequests()
                .antMatchers("/","/user/login").permitAll()//设置哪些路径可以直接访问,不需要认证
                .antMatchers("/test/index").hasRole("sale")//具有ROLE_sale的角色可以访问这个路径
                .anyRequest().authenticated()//除上面外的所有请求全部需要鉴权认证
                .and().csrf().disable();//关闭csrf防护
    }

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

}

2.这里注意的是hasRole与hasAuthority的区别是角色名字前要加上"ROLE_"

@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_sale");
        return new User("tom",new BCryptPasswordEncoder().encode("123456"),auths);
    }
}

 

四、hasAnyRole

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

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


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin() //自定义编写的登录页面
            .loginPage("/login.html")//登录页面设置
            .loginProcessingUrl("/user/login")//登录后访问路径
            .defaultSuccessUrl("/test/index")//登录成功后跳转路径
            .and().authorizeRequests()
                .antMatchers("/","/user/login").permitAll()//设置哪些路径可以直接访问,不需要认证
                .antMatchers("/test/index").hasAnyRole("sale,master")//具有ROLE_sale,ROLE_master的角色可以访问这个路径
                .anyRequest().authenticated()//除上面外的所有请求全部需要鉴权认证
                .and().csrf().disable();//关闭csrf防护
    }

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

}
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_sale,ROLE_master");
        return new User("tom",new BCryptPasswordEncoder().encode("123456"),auths);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值