Security安全框架

添加依赖

	    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

设置简单权限问题

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;


@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //请求授权规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        首页所有人可以访问,功能页只有对应有权限的人才能访问
//        /表示首页,首页所有人都能访问,所以是permitAll
//        level1只能是VIP1可以访问
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");
//      没有权限默认会到登录页面
        http.formLogin();

//        注销用户,默认跳到登录界面
 //     http.logout();
 //但是可以指定跳转位置,这里设置跳转到开始页面
        http.logout().logoutSuccessUrl("/");
  

    }
    
//认证规则
// 在springboot 2.1.X可以直接使用passwordEncoder("123456")
//  但是现在版本更新,需要用到passwordEncoder(new BCryptPasswordEncoder())密码编码
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("kuangshen").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");

    }
}

首页界面
在这里插入图片描述

若使用kuangshen登录,则只能进level1和level2,level3会报错
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
这里再额外说一个权限控制的问题,但是他跟springBoot的版本有关
在这里插入图片描述

我们现在的版本都比较新,这个权限控制好像是只能是旧版本,2.0.7/9都可以,这个权限控制就是用户是vip几的时候,就只显示几的菜单,不显示该用户没有权限的菜单,实现菜单动态化,想实现这个功能的话要先把springboot 的版本降下来
然后导入security和thyemleaf的整合包

		 <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>

这样我们在写html就可以加上security的判断,当这个用户属于vip1的时候,这段标签才会有作用
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值