快捷搜索: 王者荣耀 脱发

spring security默认表单认证

1. 添加配置类

import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { } }

在给 WebSecutiryConfig 类中加上@EnableWebSecurity 注解后,便会自动被 Spring 发现并注册(查看@EnableWebSecurity 即可看到@Configuration 注解已经存在,所以此处不需要额外添加)。

查看 WebSecurityConfigurerAdapter 类对 configure(HttpSecurity http)的定义。

protected void configure(HttpSecurity http) throws Exception { logger.debug("Using default configure(HttpSecurity). If subclassed this will potentially override subclass configure(HttpSecurity)."); http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin().and() .httpBasic(); }

可以看到 WebSecurityConfigurerAdapter 已经默认声明了一些安全特性:

    验证所有请求。 允许用户使用表单登录进行身份验证(Spring Security 提供了一个简单的表单登录页面)。 允许用户使用 HTTP 基本认证。

2. 启动服务

现在重启服务,应用新的安全配置。可以预见,在下次访问 localhost:8080 时,系统会要求我们进行表单认证。

结果很意外,无论怎么刷新,都无法看到表单登录页,为什么呢?我们可以从浏览器的开发者工具中找到蛛丝马迹(在 Chrome 浏览器中可以按快捷键 F12 调出开发者工具)。

查看浏览器发出的请求头中自动携带 Authorization 属性,由于 Spring Security 的配置刚好同时支持 HTTP 基本认证,所以并不需要在表单中重新登录。

这实际上属于浏览器的默认行为,只要在 HTTP 基本认证中成功认证过,便会自动记住一段时间,也就是说,可以跳过登录直接访问系统资源。那么如何避免这种情况的发生呢?在 IE 浏览器中,可以在控制台执行 document.execCommand(「ClearAuthenticationCache」)语句清除 HTTP 基本认证缓存,但这种方法在 Chrome 浏览器中并不适用。建议调试时直接使用浏览器的无痕模式,简单方便,可以避免很多缓存问题(在 Windows 下的 Chrome 浏览器中,可用组合键 Ctrl+Shift+n 打开浏览器的无痕模式;在 mac 下的 Chrome 浏览器中,可用组合键 Command+Shift+n 打开浏览器的无痕模式)。

经过一些小插曲,我们终于成功进入表单登录页

访问地址自动跳转到 localhost:8080/login,这正是 Spring Security 的默认登录页,只要输入正确的用户名和密码便可跳转回原访问地址。

经验分享 程序员 微信小程序 职场和发展