Spring Security 配置 Basic Authentication

1、概览

本文将带你了解如何通过 Spring Security 提供的 Basic Authentication 机制来保护 MVC 应用。

2、Spring Security 配置

使用 Java 配置来配置 Spring Security:

@Configuration
@EnableWebSecurity
public class CustomWebSecurityConfigurerAdapter {

    @Autowired private RestAuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
          .inMemoryAuthentication()
          .withUser("user1")
          .password(passwordEncoder().encode("user1Pass"))
          .authorities("ROLE_USER");
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(expressionInterceptUrlRegistry ->
                        expressionInterceptUrlRegistry.requestMatchers("/securityNone").permitAll()
                                .anyRequest().authenticated())
            .httpBasic(httpSecurityHttpBasicConfigurer -> httpSecurityHttpBasicConfigurer.authenticationEntryPoint(authenticationEntryPoint));
        http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class);
        return http.build();
    }
    
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

如上,在 SecurityFilterChain Bean 中使用 httpBasic() 来定义 Basic Authentication

也可以使用 XML 来配置:

<http pattern="/securityNone" security="none"/>
<http use-expressions="true">
    <intercept-url pattern="/**" access="isAuthenticated()" />
    <http-basic />
</http>

<authentication-manager>
    <authentication-provider>
        <user-service>
            <user name="user1" password="{noop}user1Pass" authorities="ROLE_USER" />
        </user-service>
    </authentication-provider>
</authentication-manager>

与此相关的是配置的 <http> 元素中的 <http-basic> 元素。这足以为整个应用启用 Basic Authentication。本文的重点不在于 Authentication Manager,所以这里使用基于内存的简单 Manager,并以纯文本形式定义用户和密码。

3、请求受保护的应用

首先,尝试在不提供任何凭证的情况下请求 /homepage.html

curl -i http://localhost:8080/spring-security-rest-basic-auth/api/foos/1

响应(401 Unauthorized)符合预期:

HTTP/1.1 401 Unauthorized
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=E5A8D3C16B65A0A007CFAACAEEE6916B; Path=/spring-security-mvc-basic-auth/; HttpOnly
WWW-Authenticate: Basic realm="Spring Security Application"
Content-Type: text/html;charset=utf-8
Content-Length: 1061
Date: Wed, 29 May 2013 15:14:08 GMT

通常情况下,浏览器会通过一个简单的对话框提示我们输入凭证,但由于这里使用的是 curl,所以需要自己手动在请求中设置凭证。

现在,请求相同的资源,即主页,但提供访问该主页的凭证:

curl -i --user user1:user1Pass 
  http://localhost:8080/spring-security-rest-basic-auth/api/foos/1

结果如下,服务器的响应是 200 OK 和一个 Cookie

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=301225C7AE7C74B0892887389996785D; Path=/spring-security-mvc-basic-auth/; HttpOnly
Content-Type: text/html;charset=ISO-8859-1
Content-Language: en-US
Content-Length: 90
Date: Wed, 29 May 2013 15:19:38 GMT

在浏览器中,可以正常使用应用;登录页面不是必须的,因为所有浏览器都支持 Basic Authentication,并使用对话框提示用户输入凭证。

4、进一步配置 - 入口点

默认情况下,Spring Security 提供的 BasicAuthenticationEntryPoint 会向客户端返回一个完整的 401 Unauthorized 响应页面。这种 HTML 错误表示在浏览器中渲染效果很好。相反,它并不适合其他场景,例如在 REST API 中,json 格式可能更受欢迎。

命名空间的灵活性也足以满足这一新要求。为此,可以重写入口点:

<http-basic entry-point-ref="myBasicAuthenticationEntryPoint" />

新的入口点定义为标准 Bean:

@Component
public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {

    @Override
    public void commence(
      HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx) 
      throws IOException, ServletException {
        response.addHeader("WWW-Authenticate", "Basic realm="" + getRealmName() + """);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        PrintWriter writer = response.getWriter();
        writer.println("HTTP Status 401 - " + authEx.getMessage());
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        setRealmName("Baeldung");
        super.afterPropertiesSet();
    }
}

通过直接写入 HTTP 响应,可以完全控制响应体的格式。

5、 总结

本文介绍了 Spring Security 如何配置 Basic Authentication 来保护应用。


Ref:https://www.baeldung.com/spring-security-basic-authentication