spring security入门--基于角色实现用户登录访问

kw,sSpringSecurity快速搭建_小黑孩666的博客-CSDN博客j

接上篇,我们搭建好了基本框架之后,怎么实现自定义用户及角色来登录不同的系统呢?话不多说,直接开干

一、首先创建一个自定义的配置类,继承WebSecurityConfigurerAdapter类


/**
 * EnableGlobalMethodSecurity 启用方法级别的认证
 */
@Configuration
@EnableWebSecurity //标识启用spring security 安全框架的功能
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MywebConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        PasswordEncoder passwordEncoder=passwordEncoder();

        auth.inMemoryAuthentication().withUser("zhangsan")
                // 给密码加密
                .password(passwordEncoder.encode("123456"))
                // 设置用户角色
                .roles("normal");

        auth.inMemoryAuthentication().withUser("lisi")
                // 给密码加密
                .password(passwordEncoder().encode("67890"))
                // 设置用户角色
                .roles("normal");

        auth.inMemoryAuthentication().withUser("admin")
                // 给密码加密
                .password(passwordEncoder().encode("admin"))
                // 设置用户角色
                .roles("admin","normal");

    }

    // 创建用来加密的实现类
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

二、在controller类中编写不同角色登录的代码

     // 指定normal和admin都可以访问的方法
    @RequestMapping("/helloUser")
    // @PreAuthorize 指定在方法之前进行角色的认证。
    @PreAuthorize(value = "hasAnyRole('admin','normal')")
    public String helloUser(){
        return "拥有admin,normal角色的用户";
    }

    // 指定admin专有的方法
    @RequestMapping("/admin")
    // @PreAuthorize 指定在方法之前进行角色的认证。
    @PreAuthorize(value = "hasAnyRole('admin')")
    public String helloAdmin(){
        return "我是admin角色的权限";
    }

三、运行启动类进行测试

使用zhangsan账号登录 helloUser 方法成功

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值