HTTP Basic认证是用户的用户名和密码经过 base64 编码以后,放在请求头 Authorization 字段中,从而完成用户身份认证。
配置@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic()
.and().csrf().disable();
}
工作原理
它的工作原理大概是:首先客户端发起一个未认证的请求 /private ,然后Spring Security的 FilterSecurityInterceptor 拦截器拦截这个未认证的请求,拒绝访问并抛出 AccessDeniedException 异常。然后由 ExceptionTranslationFilter 过滤器捕获异常并由 BasicAuthenticationEntryPoint 响应一个 WWW-Authenticate 的响应头。用户输入用户名和密码,点击登录,发起一个带有 Authorization 请求头的请求,进行登录认证。请求头 Authorization 的值是用户名和密码的 base64 编码。大概流程图如下所示。
BasicAuthenticationEntryPointpublic void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
response.addHeader("WWW-Authenticate", "Basic realm="" + realmName + """);
response.sendError(HttpStatus.UNAUTHORIZED.value(),
HttpStatus.UNAUTHORIZED.getReasonPhrase());
}



