在 Java API 的開發中,鑑權是不可避免的問題。 OAuth2 是一種流行的鑑權方式,它透過授權存取來保護 API 資源。本文將介紹如何在 Java API 開發中使用 OAuth2 進行鑑權。
OAuth2 簡介
OAuth2 是一種用於授權的開放標準,它允許使用者授權第三方應用程式存取他們的伺服器資源,而不必分享他們的憑證。 OAuth2 標準包括下列角色:
- Resource Owner:資源擁有者,即使用者;
- Resource Server:資源伺服器,提供資源的伺服器;
- Client:客戶端,即第三方應用程式;
- Authorization Server:授權伺服器,用於頒發存取權杖。
OAuth2 的授權程序包括以下步驟:
- Client 向Authorization Server 發送授權請求;
- Authorization Server 向Resource Owner 請求授權;
- Resource Owner 授權後,Authorization Server 傳送存取權杖給Client;
- Client 使用存取權杖向Resource Server 傳送請求;
- Resource Server 驗證存取權杖並提供資源。
OAuth2 支援多種授權類型,包括授權碼模式、密碼模式、客戶端模式、隱含授權模式等。在 Java API 開發中,通常使用授權碼模式和密碼模式。
OAuth2 授權碼模式
授權碼模式是OAuth2 中最常用的授權類型,它包含以下步驟:
- Client 向Authorization Server 發送授權請求,包括Client ID 和重定向URI;
- Authorization Server 發送登入頁面給Resource Owner,要求Resource Owner 登入並授權;
- Resource Owner 授權後,Authorization Server 向重定向URI 發送授權碼;
- Client 使用授權碼向Authorization Server 發送請求,包括Client ID 和Client Secret;
- Authorization Server 驗證Client ID 和Client Secret,如果正確,頒發存取權令牌給Client;
- Client 使用存取權杖向Resource Server 傳送請求。
在 Java API 開發中,可以使用 Spring Security OAuth2 框架實作授權碼模式的識別碼。
首先,需要在pom.xml 檔案中新增以下相依性:
<dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> <version>2.3.4.RELEASE</version> </dependency>
然後,在Spring MVC 的設定檔中新增以下設定:
<security:http pattern="/oauth/token" create-session="stateless" authentication-manager-ref="authenticationManager" xmlns="http://www.springframework.org/schema/security"> <security:intercept-url pattern="/oauth/token" access="isAuthenticated()" method="POST" /> <security:anonymous enabled="false" /> <security:http-basic entry-point-ref="clientAuthenticationEntryPoint" /> <security:custom-filter ref="clientCredentialsTokenEndpointFilter" before="BASIC_AUTH_FILTER" /> <security:access-denied-handler ref="oauthAccessDeniedHandler" /> </security:http> <security:http pattern="/api/**" create-session="never" entry-point-ref="oauthAuthenticationEntryPoint" access-decision-manager-ref="accessDecisionManager" xmlns="http://www.springframework.org/schema/security"> <security:anonymous enabled="false" /> <security:intercept-url pattern="/api/**" access="ROLE_USER" /> <security:custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" /> <security:access-denied-handler ref="oauthAccessDeniedHandler" /> </security:http> <bean id="clientAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint"> <property name="realmName" value="spring-boot-oauth2" /> <property name="typeName" value="Basic" /> </bean> <bean id="oauthAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint"> <property name="realmName" value="spring-boot-oauth2" /> <property name="typeName" value="Bearer" /> </bean> <bean id="oauthAccessDeniedHandler" class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" /> <bean id="clientCredentialsTokenEndpointFilter" class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter"> <property name="authenticationManager" ref="authenticationManager" /> </bean> <bean id="resourceServerFilter" class="org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter"> <property name="authenticationManager" ref="authenticationManager" /> </bean> <bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased" xmlns="http://www.springframework.org/schema/beans"> <constructor-arg> <list> <bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter" /> <bean class="org.springframework.security.access.vote.RoleVoter" /> <bean class="org.springframework.security.access.vote.AuthenticatedVoter" /> </list> </constructor-arg> </bean> <security:authentication-manager id="authenticationManager"> <security:authentication-provider user-service-ref="userDetailsService" /> </security:authentication-manager> <bean id="userDetailsService" class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl"> <property name="dataSource" ref="dataSource" /> </bean>
其中,/ oauth/token 是用來取得存取權杖的路徑,/api/** 是需要進行鑑權的路徑。
使用 OAuth2RestTemplate 發送請求時,需要先取得存取權杖,程式碼如下:
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(client, context); AuthorizationCodeResourceDetails details = (AuthorizationCodeResourceDetails)client.getResource(); AuthorizationCodeAccessTokenProvider provider = new AuthorizationCodeAccessTokenProvider(); Authentication auth = new UsernamePasswordAuthenticationToken(username, password); AccessTokenRequest tokenRequest = provider.createAccessTokenRequest(details, auth); OAuth2AccessToken accessToken = provider.obtainAccessToken(details, tokenRequest); restTemplate.getOAuth2ClientContext().setAccessToken(accessToken);
其中,client 是 OAuth2ProtectedResourceDetails 類型的對象,包含 Client ID 和 Client Secret 等資訊。
OAuth2 密碼模式
密碼模式是OAuth2 中適用於信任客戶端的授權類型,它包含以下步驟:
- Client 向Authorization Server 發送請求,包括Client ID、Client Secret 和Resource Owner 的使用者名稱密碼;
- Authorization Server 驗證Client ID、Client Secret 和使用者名稱密碼,如果正確,請頒發存取權杖給Client;
- Client 使用存取權杖向Resource Server 傳送請求。
在 Java API 開發中,可以使用 Spring Security OAuth2 框架實作密碼模式的識別碼。
首先,需要在pom.xml 檔案中新增以下相依性:
<dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> <version>2.3.4.RELEASE</version> </dependency>
然後,在Spring MVC 的設定檔中新增以下設定:
<security:http pattern="/oauth/token" create-session="stateless" authentication-manager-ref="authenticationManager" xmlns="http://www.springframework.org/schema/security"> <security:intercept-url pattern="/oauth/token" access="isAuthenticated()" method="POST" /> <security:anonymous enabled="false" /> <security:http-basic entry-point-ref="clientAuthenticationEntryPoint" /> <security:custom-filter ref="clientCredentialsTokenEndpointFilter" before="BASIC_AUTH_FILTER" /> <security:access-denied-handler ref="oauthAccessDeniedHandler" /> </security:http> <security:http pattern="/api/**" create-session="never" entry-point-ref="oauthAuthenticationEntryPoint" access-decision-manager-ref="accessDecisionManager" xmlns="http://www.springframework.org/schema/security"> <security:anonymous enabled="false" /> <security:intercept-url pattern="/api/**" access="ROLE_USER" /> <security:custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" /> <security:access-denied-handler ref="oauthAccessDeniedHandler" /> </security:http> <bean id="clientAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint"> <property name="realmName" value="spring-boot-oauth2" /> <property name="typeName" value="Basic" /> </bean> <bean id="oauthAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint"> <property name="realmName" value="spring-boot-oauth2" /> <property name="typeName" value="Bearer" /> </bean> <bean id="oauthAccessDeniedHandler" class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" /> <bean id="clientCredentialsTokenEndpointFilter" class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter"> <property name="authenticationManager" ref="authenticationManager" /> </bean> <bean id="resourceServerFilter" class="org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter"> <property name="authenticationManager" ref="authenticationManager" /> </bean> <bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased" xmlns="http://www.springframework.org/schema/beans"> <constructor-arg> <list> <bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter" /> <bean class="org.springframework.security.access.vote.RoleVoter" /> <bean class="org.springframework.security.access.vote.AuthenticatedVoter" /> </list> </constructor-arg> </bean> <security:authentication-manager id="authenticationManager"> <security:authentication-provider user-service-ref="userDetailsService" /> </security:authentication-manager> <bean id="userDetailsService" class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl"> <property name="dataSource" ref="dataSource" /> </bean>
其中,/ oauth/token 是用來取得存取權杖的路徑,/api/** 是需要進行鑑權的路徑。
使用OAuth2RestTemplate 發送請求時,需要先取得存取權杖,程式碼如下:
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(details, new DefaultOAuth2ClientContext()); restTemplate.getOAuth2ClientContext().setAccessToken(accesstoken);
其中,details 是ResourceOwnerPasswordResourceDetails 類型的對象,包含Client ID、Client Secret、使用者名稱和密碼等資訊。
總結
在 Java API 開發中使用 OAuth2 進行鑑權可以保護 API 資源的安全,並且可以讓使用者更方便地授權第三方應用程式存取他們的伺服器資源。本文介紹了 OAuth2 的授權碼模式和密碼模式,並且提供了使用 Spring Security OAuth2 框架實作鑑權的範例程式碼。希望可以對 Java API 開發者有幫助。
以上是Java API 開發中使用 OAuth2 鑑權的詳細內容。更多資訊請關注PHP中文網其他相關文章!

javaispopularforcross-platformdesktopapplicationsduetoits“ writeonce,runany where”哲學。 1)itusesbytiesebyTecodeThatrunsonAnyJvm-備用Platform.2)librarieslikeslikeslikeswingingandjavafxhelpcreatenative-lookingenative-lookinguisis.3)

在Java中編寫平台特定代碼的原因包括訪問特定操作系統功能、與特定硬件交互和優化性能。 1)使用JNA或JNI訪問Windows註冊表;2)通過JNI與Linux特定硬件驅動程序交互;3)通過JNI使用Metal優化macOS上的遊戲性能。儘管如此,編寫平台特定代碼會影響代碼的可移植性、增加複雜性、可能帶來性能開銷和安全風險。

Java將通過雲原生應用、多平台部署和跨語言互操作進一步提昇平台獨立性。 1)雲原生應用將使用GraalVM和Quarkus提升啟動速度。 2)Java將擴展到嵌入式設備、移動設備和量子計算機。 3)通過GraalVM,Java將與Python、JavaScript等語言無縫集成,增強跨語言互操作性。

Java的強類型系統通過類型安全、統一的類型轉換和多態性確保了平台獨立性。 1)類型安全在編譯時進行類型檢查,避免運行時錯誤;2)統一的類型轉換規則在所有平台上一致;3)多態性和接口機制使代碼在不同平台上行為一致。

JNI會破壞Java的平台獨立性。 1)JNI需要特定平台的本地庫,2)本地代碼需在目標平台編譯和鏈接,3)不同版本的操作系統或JVM可能需要不同的本地庫版本,4)本地代碼可能引入安全漏洞或導致程序崩潰。

新興技術對Java的平台獨立性既有威脅也有增強。 1)雲計算和容器化技術如Docker增強了Java的平台獨立性,但需要優化以適應不同雲環境。 2)WebAssembly通過GraalVM編譯Java代碼,擴展了其平台獨立性,但需與其他語言競爭性能。

不同JVM實現都能提供平台獨立性,但表現略有不同。 1.OracleHotSpot和OpenJDKJVM在平台獨立性上表現相似,但OpenJDK可能需額外配置。 2.IBMJ9JVM在特定操作系統上表現優化。 3.GraalVM支持多語言,需額外配置。 4.AzulZingJVM需特定平台調整。

平台獨立性通過在多種操作系統上運行同一套代碼,降低開發成本和縮短開發時間。具體表現為:1.減少開發時間,只需維護一套代碼;2.降低維護成本,統一測試流程;3.快速迭代和團隊協作,簡化部署過程。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

Atom編輯器mac版下載
最受歡迎的的開源編輯器

禪工作室 13.0.1
強大的PHP整合開發環境