SpringBoot(16)SpringSercurity认证与授权

1.搭建环境

导入启动器starter

<!--导入sercuryty-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>

2.编写Sercurity的配置

1.创建config包,并且创建Sercurity的配置类
2.添加@EnableWebSecurity注解
3.继承父类 WebSecurityConfigurerAdapte

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

}

3. 授权

1.运用的是aop思想,添加授权操作
2.授权规则:http发出请求认证,请求地址,访问角色(所有人还是指定某个人)

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/").permitAll()//所有人
                .antMatchers("/level1/**").hasRole("vip1")//指定某个人
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //没有权限会跳转到登陆页面
        http.formLogin();
    }

}

4.认证

1.inMemoryAuthentication()表示内存虚拟数据,实际上用数据库中的jdbcAuthentication()。
2.passwordEncoder(new BCryptPasswordEncoder())表示密码的编码格式,默认使用new BCryptPasswordEncoder()。
3.授权规则:添加一个用户aaa,设置密码(用new BCryptPasswordEncoder().encode(“123456”)进行解码),添加一个角色(角色可以是多个)
4.使用and()添加多个用户

   @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("aaa").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
                .and()
                .withUser("bbb").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")
                .and()
                .withUser("ccc").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3");


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值