天天看点

[3天速成Spring Security] - 04 Spring Security安全配置简介HttpSecurity的配置WebSecurity的配置

继承

WebSecurityConfigurerAdapter

类可以实现安全配置,其中常用的配置内容是

HttpSecurity

WebSecurity

HttpSecurity的配置

代码实现

  • 继承

    WebSecurityConfigurerAdapter

    ,重写

    configure(HttpSecurity)

    方法
  • 实例代码
@Override
protected void configure(HttpSecurity http) throws Exception {
	// TODO...
}
           

代码分析

  • 查看方法基类默认实现,当没有重写该方法时,此默认配置则会生效
protected void configure(HttpSecurity http) throws Exception {
	this.logger.debug("Using default configure(HttpSecurity). "
				+ "If subclassed this will potentially override subclass configure(HttpSecurity).");
	http.authorizeRequests((requests) -> requests.anyRequest().authenticated()); // 任何请求都会进行认证
	http.formLogin(); // 启用内建的登录页面m
	http.httpBasic(); // 使用HTTP Basic Auth进行认证
}
           
  • 如果希望启用Security的调试功能且输出日志,则可以给

    @EnableWebSecurity

    (debug=true)

    参数启用。【默认不启用】
    [3天速成Spring Security] - 04 Spring Security安全配置简介HttpSecurity的配置WebSecurity的配置
  • 启用后则每当有API访问时都可以在控制台看到完整的请求内容【请求信息,参与的Filter Chain】
    [3天速成Spring Security] - 04 Spring Security安全配置简介HttpSecurity的配置WebSecurity的配置

配置Security用户名及密码

  • 在application.properties中配置登录用户名,密码及角色
spring.security.user.name=jack
spring.security.user.password=12345678
spring.security.user.roles=USER,ADMIN
           
  • 配置后,Spring Security就不会再为我们生成随机密码了

WebSecurity的配置

代码实现

  • 继承

    WebSecurityConfigurerAdapter

    ,重写

    configure(WebSecurity)

    方法
  • 实例代码
@Override
public void configure(WebSecurity web) throws Exception {
	// TODO...
}
           
  • 与HttpSecurity的区别
    • 任何请求进入HttpSecurity configure的方法时都会启动过滤器链,但是启动过滤器链是很昂贵的操作,有时候并不期待经过过滤器链。当我们希望有的API不经过过滤器链的处理就允许或拒绝时,则需要在HttpSecurity的configure方法中实现。

代码分析

  • 当希望test开头的API请求不通过过滤器链时可以通过如下配置
@Override
public void configure(WebSecurity web) throws Exception {
	web.ignoring().mvcMatchers("/test/**");
}
           
  • 当用户访问

    /test/

    开头的API时,则会直接放行,不会经过过滤器链进行安全检查。通常作用于静态文件的路径等等…