Spring Security基于Java配置

时间:2022-07-16 18:27:22

Maven依赖

 1 <dependencies>
2 <!-- ... other dependency elements ... -->
3 <dependency>
4 <groupId>org.springframework.security</groupId>
5 <artifactId>spring-security-web</artifactId>
6 <version>4.2.3.RELEASE</version>
7 </dependency>
8 <dependency>
9 <groupId>org.springframework.security</groupId>
10 <artifactId>spring-security-config</artifactId>
11 <version>4.2.3.RELEASE</version>
12 </dependency>
13 </dependencies>

 

开启Spring Security

 1 @EnableWebSecurity
2 public class SecurityConfig {
3
4 @Autowired
5 public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
6 auth
7 .inMemoryAuthentication()
8 .withUser("user").password("password").roles("USER");
9 }
10 }

The SecurityConfig will:

  • 要求验证所有请求应用的URL

  • 产生一个登录表单界面

  • 只允许使用类中指定的“user”和“password”进行登录才验证通过

  • 运行用户登出(使用post方便访问“/logout”URL)

  • 第8行定义一个在内存中(in memory)的用户,用户名为“user”,密码为“password”,角色为“USER

 

 初始化

1 public class SecurityWebApplicationInitializer
2 extends AbstractSecurityWebApplicationInitializer {
3
4 public SecurityWebApplicationInitializer() {
5 super(SecurityConfig.class);
6 }
7 }

The SecurityWebApplicationInitializer 将会:

  • 自动注册springSecurityFilterChain Filter拦截所有的URL

  • 添加一个ContextLoaderListener去加载 上面定义SecurityConfig配置类

 springSecurityFilterChain Filter:负责应用的所有安全,包括保护URL的访问、验证提交的用户名和密码、重定向到登录表单等

 

自定义登录界面:修改SecurityConfig类,WebSecurityConfigurerAdapter类提供一些方便的默认设置,使应用程序快速运行。

 1 @EnableWebSecurity
2 public class SecurityConfig extends WebSecurityConfigurerAdapter {
3
4 @Override
5 protected void configure(HttpSecurity http) throws Exception {
6 http
7 .authorizeRequests()
8 .antMatchers("/resources/**").permitAll()
9 .anyRequest().authenticated()
10 .and()
11 .formLogin()
12 .loginPage("/login")
13 .permitAll()
14 .and()
15 .logout()
16 .permitAll();
17 }
18
19 // ...
20

该配置提供:

  • 验证每个请求,除了以“/resources/”开头的URL
  • 支持基于表单验证,登录页面为“/login”对应的文件
  • 支持基于http验证

其中loginPage("/login") 指示:

  • 请求验证时被重定向到 /login

  • 验证失败失败时被重定向到 /login?error

  • 登出成功时会被重定向到 /login?logout

permitAll()方法声明允许在未验证时任何访问到的资源和URL,如果不加则连访问/login 都会一直被重定向

 

 HttpSecurity类:类似与XML配置中的<http>元素,可以配置基于web的安全请求,默认下,它会作用于所有的请求,但是可以使用 requestMatcher(RequestMatcher)等类似方法进行限制

以下方法定义只有“USER”角色的用户才能访问“/”URL(即任何请求)

1 protected void configure(HttpSecurity http) throws Exception {
2 http.authorizeRequests().antMatchers("/**").hasRole("USER").and().formLogin();
3 }

常用方法:

antMatcher(String antPattern):配置只有当匹配该路径模式时才调用 HttpSecurity

authorizeRequests():限制基于HttpServletRequest之上的使用
csrf():添加CSRF支持 

configureGlobalSecurity(AuthenticationManagerBuilder auth)用来指定从何处获取用户
configure(HttpSecurity http)用来配置访问每个URL所需的对应权限

 

UserDetails
UserDetails 是一个 Spring Security 的核心接口,代表一个主体(包含于用户相关的信息)。
在 Authentication 接口中有一个方法 Object getPrincipal(); 这个方法返回的是一个安全主题,大多数情况下,这个对象可以强制转换成 UserDetails 对象,获取到UerDetails 对象之后,就可以通过这个对象的 getUserName()方法获取当前用户名。

 

自定义验证:通过暴露类型为AuthenticationProvider或者UserDetailsService的bean,使用的验证设置优先级高到低排序为AuthenticationManagerBuilder、AuthenticationProvider、UserDetailsService,即要是发现存在使用前者的配置,则后者的配置无效

通过暴露一个PasswordEncoder类型的bean来定义密码使使用何种编码,如下使用bcrypt

@Bean
public BCryptPasswordEncoder passwordEncoder() {
  return new BCryptPasswordEncoder();
}

 

开启方法注解:在任何配置类头上添加 @EnableGlobalMethodSecurity,然后就可以使用@Secured等方法级注解进行安全配置,可以为方法定义一系列属性,这些配置将会通过AccessDecisionManager来实际决定