Spring Security详解

要使用Spring Security,首先固然是得要加上依赖spring

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

这个时候咱们不在配置文件中作任何配置,随便写一个Controller安全

@RestController
public class TestController {
    @GetMapping("/hello")
    public String request() {
        return "hello";
    }
}

启动项目,咱们会发现有这么一段日志app

2020-01-05 01:57:16.482  INFO 3932 --- [           main] .s.s.UserDetailsServiceAutoConfiguration :ide

Using generated security password: 1f0b4e14-1d4c-4dc8-ac32-6d84524a57dcspring-boot

此时表示Security生效,默认对项目进行了保护,咱们访问该Controller中的接口,会见到以下登陆界面spa

这里面的用户名和密码是什么呢?此时咱们须要输入用户名:user,密码则为以前日志中的"1f0b4e14-1d4c-4dc8-ac32-6d84524a57dc",输入以后,咱们能够看到此时能够正常访问该接口.net

在老版本的Springboot中(好比说Springboot 1.x版本中),能够经过以下方式来关闭Spring Security的生效,可是如今Springboot 2中已经再也不支持日志

security:
  basic:
    enabled: false

固然像这种什么都不配置的状况下,实际上是使用的表单认证,如今咱们能够把认证方式改为HttpBasic认证(关于HTTP的几种认证方式能够参考HTTP协议整理 中的HTTP的常见认证方式)。orm

此时咱们须要在项目中加入这样一个配置类blog

/**
 * WebSecurityConfigurerAdapter是Spring提供的对安全配置的适配器
 * 使用@EnableWebSecurity来开启Web安全
 */
@Configuration
@EnableWebSecurity
public class SecrityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 重写configure方法来知足咱们本身的需求
     * 此处容许Basic登陆
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic() //容许Basic登陆
                .and()
                .authorizeRequests() //对请求进行受权
                .anyRequest()  //任何请求
                .authenticated();   //都须要身份认证
    }
}

此时重启项目,在访问/hello,界面以下

输入用户名,密码(方法与以前相同),则能够正常访问该接口。固然在这里,咱们也能够改回容许表单登陆。

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.formLogin() //容许表单登陆
            .and()
            .authorizeRequests() //对请求进行受权
            .anyRequest()  //任何请求
            .authenticated();   //都须要身份认证
}

这样又变回跟以前默认不配置同样了。

SpringSecutiry基本原理

由上图咱们能够看到,Spring Security其实就是一个过滤器链,它里面有不少不少的过滤器,就图上的第一个过滤器UsernamePasswordAuthenticationFilter是用来作表单认证过滤的;若是咱们没有配置表单认证,而是Basic认证,则第二个过滤器BasicAuthenticationFilter会发挥做用。最后一个FilterSecurityInterceptor则是用来最后一个过滤器,它的做用是用来根据前面的过滤器是否生效以及生效的结果来判断你的请求是否能够访问REST接口。若是没法经过FilterSecurityInterceptor的判断的状况下,会抛出异常。而ExceptionTranslationFIlter会捕获抛出的异常来进行相应的处理。

相关文章
相关标签/搜索