一、概述

1、什么是Spring Security

Spring Security是一个安全框架

2、相对于Shiro的优缺点

优点

Spring Security基于Spring开发,权限更加方便,功能更强大、社区资源更丰富、可以和Spring Boot,Spring Cloud无缝集成。

缺点

与Shiro相比,其配置和使用比较复杂,并且比较依赖Spring容器。

选择原因

Spring Boot,Spring Cloud出来之后,简化了Spring Security的配置。

3、核心功能

(1)认证:通过用户名和密码登录后,让系统知道当前用户的角色(确认用户是否可以访问当前系统)

(2)授权:系统根据当前用户的角色,授予对应的权限(确认用户在当前系统下拥有的权限)

4、三个对象

30f9d4545e7813f8571c3e2ea284d629.png

二、First Spring Security

1、配置

org.springframework.boot

spring-boot-starter-security

2、默认用户名密码

运行生成默认密码

// 原理:通过uuid生成默认密码

Private String password = UUID.randomUUID().toString()

f5c912b7ee6699b4fa9687d101c42479.png

访问/hello自动跳转/login,登陆后跳转/hello

c54708224bf1deffff45384a5dfab5a7.png

be8cb0c7a90268c10f185dc2c83f150d.png

3、在配置文件中设置用户名密码

由于密码是根据uuid随机生成的,每次启动密码都会改变,所以,可以在配置文件中配置用户名和密码,设置之后,控制台就不会再输出密码了。登录直接输入自己设置的用户名和密码即可。

spring:

security:

user:

name: yang

password: 1234

三、基于内存的认证和授权

1、基于内存的认证

编写配置文件,继承 WebSecurityConfigurerAdapter 重写configure方法,指定用户名和密码(会覆盖掉配置文件中的用户名和密码)

要配置加密方式不然会报错。

@Configuration

@EnableWebSecurity // 启用Spring Security

public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Bean // BCryptPasswordEncoder加密方式

public PasswordEncoder passwordEncoder(){

//return new BCryptPasswordEncoder(); // 使用bcr方式加密

return NoOpPasswordEncoder.getInstance(); // 不加密

}

@Override

protected void configure(AuthenticationManagerBuilder auth) throws Exception {

auth.inMemoryAuthentication()

.withUser("yang")

.password("123")

.roles("admin")

.and()

.withUser("meng")

.password("123")

.roles("user");

}

}

2、基于内存的角色授权

(1)给用户指定角色

上面认证的时候,添加.roles("user”) 即为给用户指定了角色

(2)在方法上添加注解

@EnableGlobalMethodSecurity(prePostEnabled = true) // 会拦截注解了@PreAuthrize注解的配置

(3)授权

@RestController

@RequestMapping("/hello")

public class HelloController {

@GetMapping

public String hello(){

return "Hello Spring Security";

}

@GetMapping("/helloAdmin")

@PreAuthorize("hasAnyRole('admin')") // 只有admin可以访问

public String helloAdmin(){

return "Hello Spring Security Admin";

}

@GetMapping("/helloUser")

@PreAuthorize("hasAnyRole('admin', 'user')") // admin和user都可以访问

public String helloUser(){

return "Hello Spring Security User";

}

}

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐