Spring boot-security 分布式安全框架 (一)
1. 概述
基本上,在所有的开发的系统中,都必须做认证(authentication)和授权(authorization),以保证系统的安全性。
2. 快速入门
Spring Security ,实现访问 API 接口时,需要首先进行登录,才能进行访问。
2.1 依赖引入
在 pom.xml
文件中,引入相关依赖。
<dependencies>
<!-- 实现对 Spring MVC 的自动化配置 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 实现对 Spring Security 的自动化配置 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
2.2 Application.java
@SpringBootApplication
public class ZtreeApplication {
public static void main(String[] args) {
SpringApplication.run(ZtreeApplication.class, args);
}
}
2.3 配置文件
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启对 Spring Security 注解的方法,进行权限验证。
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 重写 #configure(AuthenticationManagerBuilder auth) 方法,实现 AuthenticationManager 认证管理器。
*
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.
// <X> 使用内存中的 InMemoryUserDetailsManager
inMemoryAuthentication()
// <Y> 不使用 PasswordEncoder 密码编码器
.passwordEncoder(NoOpPasswordEncoder.getInstance())
// <Z> 配置 admin 用户
.withUser("admin").password("admin").roles("ADMIN")
// <Z> 配置 normal 用户
.and().withUser("normal").password("normal").roles("NORMAL");
}
/**
* 重写 #configure(HttpSecurity http) 方法,主要配置 URL 的权限控制。
*
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// 配置请求地址的权限
.authorizeRequests()
.antMatchers("/user/home").permitAll() // 所有用户可以访问
.antMatchers("/user/admin").hasRole("ADMIN") //需要有ADMIN角色的用户可以访问
.antMatchers("/user/normal").access("hasRole('ROLE_NORMAL')") //需要 NORMAL 角色
// 任何请求,访问的用户都需要经过认证
.anyRequest().authenticated()
.and()
// <Y> 设置 Form 表单登录
.formLogin()
//.loginPage("/login") // 登录 URL 地址
.permitAll() // 所有用户可访问
.and()
// 配置退出相关
.logout()
// .logoutUrl("/logout") // 退出 URL 地址
.permitAll(); // 所有用户可访问
}
}
2.4 测试
/**
* <p>
* 前端控制器
* </p>
*
* @author XiaoCoder
* @since 2021-04-30
*/
@RestController
@AllArgsConstructor
@RequestMapping("/user")
public class UserController {
@PreAuthorize("hasAnyRole('ROLE_NORMAL')")
@ApiOperation(value = "springSecurity+Oauth2,测试user登录",
notes = "springSecurity+Oauth2,测试user登录")
@GetMapping("/normal")
public String normal() {
return "hello 我是normal用户 !";
}
@PreAuthorize("hasRole('ROLE_ADMIN')")
@ApiOperation(value = "springSecurity+Oauth2,测试admin登录",
notes = "springSecurity+Oauth2,测试admin登录")
@GetMapping("/admin")
public String admin() {
return "hello 我是管理员!! !";
}
@PermitAll
@ApiOperation(value = "springSecurity+Oauth2,测试admin登录",
notes = "springSecurity+Oauth2,测试admin登录")
@GetMapping("/home")
public String home() {
return "hello 我是首页!! !";
}
}