首頁 >Java >java教程 >OAuth Spring 啟動

OAuth Spring 啟動

Linda Hamilton
Linda Hamilton原創
2024-09-20 18:17:311065瀏覽

OAuth Spring Boot

介紹

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中有四種角色:資源擁有者、客戶端、授權伺服器和資源伺服器。

  1. 資源擁有者:擁有客戶端正在存取的資源的使用者。

2.Client:代表使用者要求存取資源的應用程式。

3.授權伺服器:使用者驗證成功後向客戶端頒發存取權杖的伺服器。

4.資源伺服器:保存客戶端正在存取的資源的伺服器。

OAuth 2.0 流程

OAuth 2.0 流程涉及以下步驟:

使用者要求從第三方應用程式存取受保護的資源。

  1. 第三方應用程式將使用者重新導向至 OAuth 提供者以取得存取權杖。

  2. 使用者登入OAuth提供者並授予第三方應用程式存取受保護資源的權限。

  3. OAuth 提供者向第三方應用程式頒發存取權杖。

  4. 第三方應用程式使用存取權杖代表使用者存取受保護的資源。

現在我們已經了解了 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());
}

}`

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

  1. 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.

  2. 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.

  3. 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).

  4. 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.

  5. 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.

  6. 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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn