环境
操作系统:
Windows 10 x64
集成开发环境:
Spring Tool Suite 4
Version: 4.12.1.RELEASE
Build Id: 202110260750
浏览器(客户端):
Google Chrome
版本 97.0.4692.71(正式版本) (64 位)
项目结构
参考:Spring Security - 02 从 SecurityContextHolder 中获取用户信息
新建 WebSecurityConfigurer
配置类,使用 Basic HTTP 认证方式(第 13 行):
package com.mk.security.config.annotation.web.configuration;
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;
//@Configuration
@EnableWebSecurity
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic();
http.authorizeRequests((requests) -> requests.anyRequest().authenticated());
// http.authorizeRequests().anyRequest().authenticated();
}
}
测试
启动项目,打开浏览器,如果你已经登录,那么请先清除过去一小时的浏览数据,防止遗留的认证信息干扰本次测试。
访问 http://localhost:8080/principal,可以看到,现在的登录页面和之前的不一样:
注意:不建议在 HTTP 环境下使用,因为其使用 Base64 对用户名和密码进行编码,然后将这些信息放在 Authorization 请求头中。在 HTTP 环境下使用 Basic HTTP 认证方式,用户名和密码存在泄露的风险。
参考
Web technology for developers > HTTP > HTTP authentication
Web technology for developers > HTTP > HTTP headers > Authorization
Web technology for developers > HTTP > HTTP headers > WWW-Authenticate