SpringSecurity入门

SpringSecurity简单入门,新手易懂

1、要实现SpringSecurity的功能,首先我们要去继承WebSecurityConfigurerAdapter类!

2、认证。
重写configure(AuthenticationManagerBuilder auth)
方法,对用户进行认证
如:用户名=小白说Java,密码=123456,认证以此信息登陆者为vip1和vip2角色,一个用户可以认证多个角色

    //用户认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //这些数据正常在数据库里读
        //为用户认证权限
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("小白说Java").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
                .and().withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and().withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }

3、授权。
重写configure(HttpSecurity http)方法。对不同角色授予访问页面的权限。
如:
level1下的所有接口访问权限均给了vip1角色。
故为vip1角色的用户可以访问这些页面。

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所有人可以访问,功能页只有对应权限的人可以访问

        //授权请求
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //如果用户没有权限则自动跳到SpringSecuruty自带的登录页面
        http.formLogin();
         //如果需要跳到自己写的登录页面,
        //则这么写:http.formLogin().loginPage("/login.html")

        //开启SpringSecuruty自带注销功能
        //SpringSecuruty同时自带了登出的配置,其默认地址为/logout
        //只要开启此功能,当跳转到/logout即完成注销!
        http.logout();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值