<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # Spring REST 自定義令牌認證示例 > 原文: [https://howtodoinjava.com/spring-restful/custom-token-auth-example/](https://howtodoinjava.com/spring-restful/custom-token-auth-example/) 通過使用 Spring REST 和 Spring Security 5 創建的方法,學習將 **基于自定義令牌的身份驗證** 添加到 REST API。 將通過。 所有其他請求將返回`HTTP 403`響應。 ## 1\. Spring Security 依賴 包括以下依賴項以使用 Spring Security 類和接口。 `pom.xml` ```java <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>5.1.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>5.1.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>5.1.5.RELEASE</version> </dependency> ``` ## 2\. 擴展`AbstractPreAuthenticatedProcessingFilter` 創建一個類并擴展[`AbstractPreAuthenticatedProcessingFilter`](https://github.com/spring-projects/spring-security/blob/master/web/src/main/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilter.java)。 它是用于處理過濾器的基類,這些過濾器處理**預認證的**認證請求,其中假定主體已經由外部系統認證。 默認情況下,當身份驗證嘗試失敗時,過濾器鏈將繼續進行,以允許其他身份驗證機制處理請求。 如果發現令牌無效,它將有助于將請求傳遞給其他安全過濾器(例如,表單登錄名)。 `getPreAuthenticatedPrincipal()`方法有助于從當前請求中讀取`auth`標頭值。 `PreAuthTokenHeaderFilter.java` ```java import javax.servlet.http.HttpServletRequest; import org.springframework.security.web.authentication .preauth.AbstractPreAuthenticatedProcessingFilter; public class PreAuthTokenHeaderFilter extends AbstractPreAuthenticatedProcessingFilter { private String authHeaderName; public PreAuthTokenHeaderFilter(String authHeaderName) { this.authHeaderName = authHeaderName; } @Override protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) { return request.getHeader(authHeaderName); } @Override protected Object getPreAuthenticatedCredentials(HttpServletRequest request) { return "N/A"; } } ``` 這是可選方法。 應用程序可能會決定立即簡單地返回認證失敗錯誤。 ## 3\. 配置`AuthenticationManager`并添加到`HttpSecurity` 我們需要設置身份驗證管理器,它將處理身份驗證過程并決定如何處理成功和失敗方案。 添加身份驗證管理器后,我們可以將`PreAuthTokenHeaderFilter`添加到`HttpSecurity`。 如果出現任何身份驗證錯誤,則默認情況下將處理該錯誤[`ExceptionTranslationFilter`](https://docs.spring.io/spring-security/site/docs/4.2.11.RELEASE/apidocs/org/springframework/security/web/access/ExceptionTranslationFilter.html),該錯誤會在 Spring 轉發到默認身份驗證錯誤頁面。 如果要以不同方式顯示認證錯誤響應,則需要創建自定義`ExceptionTranslationFilter`類。 `AuthTokenSecurityConfig.java` ```java import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.annotation.Order; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; 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; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.access.ExceptionTranslationFilter; import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint; @Configuration @EnableWebSecurity @PropertySource("classpath:application.properties") @Order(1) public class AuthTokenSecurityConfig extends WebSecurityConfigurerAdapter { @Value("${howtodoinjava.http.auth.tokenName}") private String authHeaderName; //TODO: retrieve this token value from data source @Value("${howtodoinjava.http.auth.tokenValue}") private String authHeaderValue; @Override protected void configure(HttpSecurity httpSecurity) throws Exception { PreAuthTokenHeaderFilter filter = new PreAuthTokenHeaderFilter(authHeaderName); filter.setAuthenticationManager(new AuthenticationManager() { @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String principal = (String) authentication.getPrincipal(); if (!authHeaderValue.equals(principal)) { throw new BadCredentialsException("The API key was not found " + "or not the expected value."); } authentication.setAuthenticated(true); return authentication; } }); httpSecurity. antMatcher("/api/**") .csrf() .disable() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .addFilter(filter) .addFilterBefore(new ExceptionTranslationFilter( new Http403ForbiddenEntryPoint()), filter.getClass() ) .authorizeRequests() .anyRequest() .authenticated(); } } ``` ## 4\. 注冊安全過濾器 傳統上,spring security 在`DelegatingFilterProxy`基于 XML 的配置中以`web.xml`文件為起點。 `web.xml` ```java <!-- Spring Security --> <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy </filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> ``` 在 Java 配置中,我們可以通過刪除類`AbstractSecurityWebApplicationInitializer`來實現相同的效果。 `SpringSecurityInitializer.java` ```java import org.springframework.security.web.context .AbstractSecurityWebApplicationInitializer; public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer { //no code needed } ``` ## 4\. Spring REST 自定義令牌認證演示 #### 4.1. 標頭中沒有身份驗證令牌 `API 請求` ```java HTTP GET http://localhost:8080/SpringRestExample/api/rest/employee-management/employees/ ``` `API 響應` ```java HTTP Status - 403 – Forbidden Type Status - Report Message Access - Denied Description - The server understood the request but refuses to authorize it. ``` #### 4.2. 標頭中的身份驗證令牌不正確 `API 請求` ```java HTTP GET http://localhost:8080/SpringRestExample/api/rest/employee-management/employees/ AUTH_API_KEY: xyz123 ``` `API 響應` ```java HTTP Status - 403 – Forbidden Type Status - Report Message Access - Denied Description - The server understood the request but refuses to authorize it. ``` #### 4.2. 標頭中的身份驗證令牌有效 `API 請求` ```java HTTP GET http://localhost:8080/SpringRestExample/api/rest/employee-management/employees/ AUTH_API_KEY: abcd123456 ``` `API 響應` ```java HTTP Status - 200 OK { //response body } ``` [下載源碼](https://howtodoinjava.com/wp-content/downloads/SpringRestExample.zip) 學習愉快!
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看