介紹
OAuth 2.0 是一個授權框架,使第三方應用程式能夠代表使用者存取受保護的資源,而無需使用者的憑證。這是透過使用存取權杖來實現的,存取權杖由 OAuth 提供者頒發並由第三方應用程式用來存取用戶的資源。
Spring Boot 是一個用 Java 建立 Web 應用程式的流行框架。它提供了一套強大的工具來建立安全且可擴展的 Web 應用程序,非常適合實施 OAuth 2.0。
在這篇文章中,我們將完成使用 Spring Boot 實作 OAuth 2.0 所需的步驟。我們將使用 Spring Security OAuth 2.0 框架來實現 OAuth 2.0 授權和認證。
開始之前,讓我們先了解 OAuth 2.0 流程,以便更好地了解它的工作原理。
OAuth 2.0 概述
OAuth 2.0 是一種授權協議,允許第三方應用程式代表使用者存取資源。它使用存取權杖來提供對成功身份驗證後獲得的資源的存取權限。 OAuth 2.0中有四種角色:資源擁有者、客戶端、授權伺服器和資源伺服器。
- 資源擁有者:擁有客戶端正在存取的資源的使用者。
2.Client:代表使用者要求存取資源的應用程式。
3.授權伺服器:使用者驗證成功後向客戶端頒發存取權杖的伺服器。
4.資源伺服器:保存客戶端正在存取的資源的伺服器。
OAuth 2.0 流程
OAuth 2.0 流程涉及以下步驟:
使用者要求從第三方應用程式存取受保護的資源。
第三方應用程式將使用者重新導向至 OAuth 提供者以取得存取權杖。
使用者登入OAuth提供者並授予第三方應用程式存取受保護資源的權限。
OAuth 提供者向第三方應用程式頒發存取權杖。
第三方應用程式使用存取權杖代表使用者存取受保護的資源。
現在我們已經了解了 OAuth 2.0 流程,讓我們繼續使用 Spring Boot 來實現它。
使用 Spring Boot 實作 OAuth 2.0
新增依賴項
首先,將必要的依賴項新增至您的 Spring Boot 專案中。您可以透過將以下依賴項新增至 pom.xml 檔案來實現此目的:
`
org.springframework.boot
spring-boot-starter-oauth2-client
org.springframework.security
spring-security-oauth2-jose
`
配置 OAuth 2.0
接下來,透過建立擴充 WebSecurityConfigurerAdapter 的類別來設定 OAuth 2.0。這是一個例子:
`@配置
@EnableWebSecurity
公用類別 SecurityConfig 擴充 WebSecurityConfigurerAdapter {
@Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/oauth2/**", "/login/**", "/logout/**") .permitAll() .anyRequest() .authenticated() .and() .oauth2Login() .loginPage("/login") .defaultSuccessURL("/home") .and() .logout() .logoutSuccessUrl("/") .logoutUrl("/logout") .and() .csrf().disable(); }
}`
此配置允許任何人存取 /oauth2/、/login/ 和 /logout/** 端點。所有其他端點都需要身份驗證。當使用者透過 OAuth 2.0 登入時,他們將被重定向到 /home 端點。當他們註銷時,他們將被重定向到 / 端點。
產生令牌
要產生令牌,您可以使用 spring-security-oauth2-jose 依賴項中的 JwtBuilder 類別。這是一個例子:
`導入 org.springframework.security.oauth2.jwt.Jwt;
導入 org.springframework.security.oauth2.jwt.JwtBuilder;
導入 org.springframework.security.oauth2.jwt.Jwts;
導入 org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
導入java.security.KeyPair;
導入 java.security.KeyPairGenerator;
導入 java.security.NoSuchAlgorithmException;
導入 java.time.Instant;
導入 java.util.Date;
公共類別TokenGenerator {
public static void main(String[] args) throws NoSuchAlgorithmException { // Generate a key pair KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); KeyPair keyPair = keyPairGenerator.generateKeyPair(); // Build the JWT JwtBuilder jwtBuilder = Jwts.builder() .setIssuer("https://example.com") .setAudience("https://example.com/resources") .setId("123") .setSubject("user@example.com") .setExpiration(Date.from(Instant.now().plusSeconds(3600))) .setIssuedAt(new Date()) .signWith(new NimbusJwtEncoder(keyPair.getPrivate())); Jwt jwt = jwtBuilder.build(); System.out.println(jwt.getTokenValue()); }
}`
此程式碼產生金鑰對,使用必要的聲明建立 JWT,並使用私鑰對其進行簽署。產生的令牌將列印到控制台。
請注意,這只是如何產生令牌的範例。在實踐中,您可能希望安全地儲存私鑰並使用不同的方法來產生過期時間。
配置 OAuth 2.0 客戶端
要在應用程式中使用 OAuth 2.0,您需要設定客戶端。在 Spring Boot 中,您可以透過在 application.properties 檔案中新增屬性來實現此目的。這是一個例子:
spring.security.oauth2.client.registration.example.client-id=client-id
spring.security.oauth2.client.registration.example.client-secret=client-secret
spring.security.oauth2.client.registration.example.scope=read,write
spring.security.oauth2.client.registration.example.redirect-uri=http://localhost:8080/login/oauth2/code/example
spring.security.oauth2.client.provider.example.authorization-uri=https://example.com/oauth2/authorize
spring.security.oauth2.client.provider.example.token-uri=https://example.com/oauth2/token
spring.security.oauth2.client.provider.example.user-info-uri=https://example.com/userinfo
spring.security.oauth2.client.provider.example.user-name-attribute=name
This configuration sets up an OAuth 2.0 client with the client ID and client secret provided by the example registration. It also sets the desired scope, redirect URI, and authorization, token, and user info URIs for the provider. Finally, it specifies that the user's name should be retrieved from the name attribute in the user info response.
Use the Token
Once you have a token, you can use it to access protected resources. For example, you can make an authenticated request to a resource server using the RestTemplate class. Here's an example:
`import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
public class ResourceClient {
public static void main(String[] args) { // Create a RestTemplate RestTemplate restTemplate = new RestTemplate(); // Set the authorization header HttpHeaders headers = new HttpHeaders(); headers.setBearerAuth("token"); // Make the request HttpEntity<string> entity = new HttpEntity(headers); ResponseEntity<string> response = restTemplate.exchange( "https://example.com/resource", HttpMethod.GET, entity, String.class ); // Print the response body System.out.println(response.getBody()); } </string></string>
}`
This code sets the authorization header to the JWT token and makes a GET request to the /resource endpoint on the resource server. The response body is printed to the console.
Protect Endpoints
To protect endpoints in your Spring Boot application, you can use annotations provided by Spring Security. For example, you can use the @PreAuthorize annotation to ensure that a user has a specific role before they can access an endpoint. Here's an example:
`import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@GetMapping("/admin") @PreAuthorize("hasRole('ADMIN')") public String adminEndpoint() { return "Hello, admin!"; }
}`
This code defines a controller with an endpoint that requires the user to have the ADMIN role in order to access it. If the user does not have the required role, they will receive a 403 Forbidden error.
Test the OAuth 2.0 flow
Start the application First, start the Spring Boot application that you’ve configured to use OAuth 2.0. You can do this by running the main() method in your application's main class.
Navigate to the login endpoint Next, navigate to the /login endpoint in your browser. For example, if your application is running on localhost:8080, you would go to http://localhost:8080/login.
Authenticate with the authorization server When you navigate to the login endpoint, your application will redirect you to the authorization server to authenticate. Depending on the authorization server, you may be prompted to enter your username and password, or you may be presented with a login button to authenticate with a third-party provider (such as Google or Facebook).
Grant access After you authenticate, you will be prompted to grant access to the scopes requested by the client. For example, if the client requested the read and write scopes, you may be prompted to grant access to read and write the user's data.
Receive the token Once you grant access, you will be redirected back to your application with an OAuth 2.0 token. This token can then be used to access protected resources.
For example, if you protected an endpoint with the @PreAuthorize annotation as described in the previous example, you could navigate to that endpoint and test whether or not you have access. If you have the required role, you will see the response from the endpoint. If you do not have the required role, you will receive a 403 Forbidden error.
以上是OAuth Spring 啟動的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

Java的五大特色是多態性、Lambda表達式、StreamsAPI、泛型和異常處理。 1.多態性讓不同類的對象可以作為共同基類的對象使用。 2.Lambda表達式使代碼更簡潔,特別適合處理集合和流。 3.StreamsAPI高效處理大數據集,支持聲明式操作。 4.泛型提供類型安全和重用性,編譯時捕獲類型錯誤。 5.異常處理幫助優雅處理錯誤,編寫可靠軟件。

java'stopfeatureSnificallyenhanceItsperformanCandScalability.1)對象 - 方向clincipleslike-polymormormormormormormormormormormormorableableflexibleandscalablecode.2)garbageCollectionAutectionAutoctionAutoctionAutoctionAutoctionAutoctionAutoMenateMememorymanateMmanateMmanateMmanagementButCancausElatemention.3)

JVM的核心組件包括ClassLoader、RuntimeDataArea和ExecutionEngine。 1)ClassLoader負責加載、鏈接和初始化類和接口。 2)RuntimeDataArea包含MethodArea、Heap、Stack、PCRegister和NativeMethodStacks。 3)ExecutionEngine由Interpreter、JITCompiler和GarbageCollector組成,負責bytecode的執行和優化。

Java'ssafetyandsecurityarebolsteredby:1)strongtyping,whichpreventstype-relatederrors;2)automaticmemorymanagementviagarbagecollection,reducingmemory-relatedvulnerabilities;3)sandboxing,isolatingcodefromthesystem;and4)robustexceptionhandling,ensuringgr

Javaoffersseveralkeyfeaturesthatenhancecodingskills:1)對象 - 方向 - 方向上的allowslowsmodelowsmodelingreal-worldentities

thejvmisacrucialcomponentthatrunsjavacodebytranslatingitolachine特定結構,影響性能,安全性和便攜性。 1)theclassloaderloader,links andinitializesClasses.2)theexecutionEngineExecutionEngineExecutionEngineExecuteNexeCuteByteCuteByteCuteByTecuteByteCuteByteCuteBytecuteBytecuteByteCoDeinintolachineinstructionsions.3)Memo.3)Memo


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。