Spring Security 入门 基于注解控制方法级权限

默认方法级权限控制是关闭的,要手动开启@EnableGlobalMethodSecurity(prePostEnabled = true)

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true) //默认方法级权限控制是关闭的,要手动开启
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginPage("/login/page")
                .loginProcessingUrl("/login")
                .and()
                .authorizeRequests()
                .antMatchers("/login/page").permitAll()
                .anyRequest().authenticated()
        ;
        http.csrf().disable();
    }
}

给方法添加权限控制@PreAuthorize("hasAuthority('aa')") @PreAuthorize("hasRole('ADMIN')")

@RestController
public class HelloController {

    @RequestMapping("hello")
    public String hell() {
        return "Hello World";
    }

    @PreAuthorize("hasAuthority('aa')")
    @RequestMapping("say")
    public String say() {
        return "say...";
    }

    @PreAuthorize("hasRole('ADMIN')")
    @RequestMapping("run")
    public String run() {
        return "run...";
    }
}

给用户权限和角色

@Slf4j
@Component
public class CustomUserDetailService implements UserDetailsService {

    @Autowired
    public PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //模拟用户可以在数据库查询到
        if ("devin".equals(username)) {
            return new User("devin", passwordEncoder.encode("1234"),
                    //这个给的权限标识符为 aa, 角色为ROLE_ADMIN(这里要注意加上前缀ROLE_标识是角色)
                    AuthorityUtils.commaSeparatedStringToAuthorityList("aa, ROLE_ADMIN"));
        }
        throw new UsernameNotFoundException("用户名输入错误");
    }
}

登录 devin/1234 因为有权限,所以都可以访问。
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述


在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值