SpringSecurity权限常用的代码讲解

请大家务必仔细阅读代码中的注释, 讲解的非常详细 !!!

package com.maxheng.config;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

// AOP : 拦截器
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //链式编程
    @Override              /*http安全策略*/
    protected void configure(HttpSecurity http) throws Exception {  //固定的官方架子
        //首页所有人都可以访问, 功能页面只能对应有权限的人才能访问

        //   |    认证请求    |  |    添加地址    | 所有人都可以访问|
        http.authorizeRequests().antMatchers("/").permitAll()
        //          level1 下所有页面, vip1才可以访问
        .antMatchers("/level1/**").hasAnyRole("vip1")
        .antMatchers("/level2/**").hasAnyRole("vip2")
        .antMatchers("/level3/**").hasAnyRole("vip3");

        //没有权限默认会到登录页面, 需要开启登录的页面
               //login
        http.formLogin();
    }


//    @Override             /*这个是后期通过数据库权限访问的自行baidu*/
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.jdbcAuthentication()
//    }


    // 密码加密编码: passwordEncode
    //在 Spring Security 5.0+ 新增了加密方式 ~
    //如果下面明文密码不加密会服务器报错 500 因为可以反编译
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {

                             /*这些数据正常从数据库中读写*/
//                                                     设置密码加密的方式
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
//                user              密码(加密后的)                                              角色
                .withUser("zhang").password(new BCryptPasswordEncoder().encode("111")).roles("vip1", "vip2")
                .and()  // 拼接符号 如果添加不同的用户或者权限使用 .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("111")).roles("vip1", "vip2", "vip2")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("111")).roles("vip1");
    }
}

以下 springboot2.2版本服务器会报错 500(2.1不会)
在这里插入图片描述
通过数据库来做权限管理的方法
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Max恒

为了开源加油 ! !

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值