【SpringBoot】Spring Security的简单应用

一、概念

两个操作:

1、认证(Authentication):确认用户可否访问当前系统

2、授权(Authorization):确认用户在当前系统中拥有的功能权限

二、例子

1.pom.xml

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

2.SecurityConfig配置类

继承WebSecurityConfigurerAdapter

public class SecurityConfig extends WebSecurityConfigurerAdapter{
    //连接Redis数据库
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Resource(name = "stringRedisTemplate")
    ValueOperations<String,String>valueOperations;
}

3.用户认证

重写configure方法

AuthenticationManagerBuilder创建用户及其对应角色

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
//user用户的用户角色为“USER”    
auth.inMemoryAuthentication().withUser(valueOperations.get("user")).password(passwordEncode().encode(valueOperations.get("user_password"))).roles("USER");
//dbm用户的用户角色为“DBM”
auth.inMemoryAuthentication().withUser(valueOperations.get("dbm")).password(passwordEncode().encode(valueOperations.get("dbm_password"))).roles("DBM");    
//admin用户的用户角色为“ADMIN”
auth.inMemoryAuthentication().withUser(valueOperations.get("admin")).password(passwordEncode().encode(valueOperations.get("admin_password"))).roles("ADMIN");
}

4.用户授权

利用HttpSecurity的authorizeRequests()方法处理URL访问策略

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception{
    httpSecurity.authorizeRequests()
                //所有用户均可访问该地址
                .antMatchers("/alllogin").permitAll()
                //只有是“ADMIN”的用户角色才可访问该地址
                .antMatchers("/adminlogin").hasRole("ADMIN")
                //其余所有请求均需验证
                .anyRequest().authenticated()
                .and()
                .logout()
                .permitAll()
                .and()
                .formLogin();
}

5.控制类

@RestController
public class LoginController {
    @RequestMapping("/alllogin")
    public String all() {
        return "hello world no security";
    }

    //设置访问该地址的用户权限,只有用户角色为“DBM”才能访问该地址
    @PreAuthorize("hasRole('ROLE_DBM')")
    @RequestMapping("/dbmlogin")
    public String dbm(Authentication authentication) {
        return "hello world must DBM security" + authentication.getName();
    }

    @RequestMapping("/adminlogin")
    public String admin(Authentication authentication){
        return "hello world must security"+authentication.getName();
    }
}

6.结果

结果输入地址栏
/alllogin/dbmlogin/adminlogin
Username和Passwordusererrorerror
dbmerror
adminerror
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

秃头的少女

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值