Spring Security 基礎身份驗證

Spring Security
Remote
1
06:31 PM · Nov 29 ,2025

1. 概述本教程將解釋如何設置、配置和自定義 基本身份驗證與 Spring。我們將在此簡單的 Spring MVC 示例的基礎上,使用 Spring Security 提供的 Basic Auth 機制來保護 MVC 應用程序的 UI。

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();
    }
}

在這裏,我們使用 httpBasic() 元素來定義 Basic Authentication 在 SecurityFilterChain bean 中

我們也可以使用 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-basic 元素在配置的 main http 元素中。 這足以啓用整個應用程序的 Basic Authentication。 由於我們沒有關注 Authentication Manager 在本教程中,我們將使用內存管理器,用户和密碼以純文本定義。

Web 應用程序啓用 Spring Security 的 web.xml 已經在 Spring Logout 教程中討論過了。

3. 消費受保護的應用

使用 curl 命令是消費受保護應用的首選工具。

首先,我們嘗試請求 /homepage.html 頁面,但不提供任何安全憑據:

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

我們收到的響應是預期的 401 未授權 以及 Basic Authentication Challenge

HTTP/1.1 401 未授權
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 Response,我們現在可以完全控制響應體格式。

5. Maven 依賴項關於 Spring Security 的 Maven 依賴項,在《Spring Security 與 Maven》一文中已經討論過。我們需要在運行時同時擁有 spring-security-webspring-security-config

6. 結論

在本文中,我們使用 Spring Security 和 Basic Authentication 對 MVC 應用程序進行了安全保護。我們討論了 XML 配置,並使用簡單的 curl 命令消費了該應用程序。最後,我們控制了精確的錯誤消息格式,從標準 HTML 錯誤頁面移動到自定義的文本或 JSON 格式。

當項目在本地運行時,樣本文檔可以在以下網址訪問:

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

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.