首页 > Java > java教程 > 正文

OAuth Spring Boot

Linda Hamilton
发布: 2024-09-20 18:17:31
原创
1060 人浏览过

OAuth Spring Boot

Introduction

OAuth 2.0 is an authorization framework that enables third-party applications to access protected resources on behalf of a user without requiring the user’s credentials. This is achieved through the use of access tokens, which are issued by an OAuth provider and used by third-party applications to access the user’s resources.

Spring Boot is a popular framework for building web applications in Java. It provides a powerful set of tools for building secure and scalable web applications and is well-suited for implementing OAuth 2.0.

In this blog post, we will go through the steps required to implement OAuth 2.0 using Spring Boot. We will use the Spring Security OAuth 2.0 framework to implement OAuth 2.0 authorization and authentication.

Before we start, let’s first go through the OAuth 2.0 flow to get a better understanding of how it works.

Overview of OAuth 2.0

OAuth 2.0 is an authorization protocol that allows third-party applications to access resources on behalf of a user. It uses access tokens to provide access to resources, which are obtained after successful authentication. There are four roles in OAuth 2.0: Resource Owner, Client, Authorization Server, and Resource Server.

  1. Resource Owner: The user who owns the resource that is being accessed by the client.

2.Client: The application that is requesting access to the resource on behalf of the user.

3.Authorization Server: The server that issues access tokens to the client after successful authentication of the user.

4.Resource Server: The server that holds the resource that is being accessed by the client.

OAuth 2.0 Flow

The OAuth 2.0 flow involves the following steps:

User requests access to a protected resource from a third-party application.

  1. The third-party application redirects the user to an OAuth provider to obtain an access token.

  2. The user logs in to the OAuth provider and grants permission to the third-party application to access the protected resource.

  3. The OAuth provider issues an access token to the third-party application.

  4. The third-party application uses the access token to access the protected resource on behalf of the user.

Now that we have an understanding of the OAuth 2.0 flow, let’s move on to implementing it using Spring Boot.

Implementing OAuth 2.0 using Spring Boot

Add dependencies
First, add the necessary dependencies to your Spring Boot project. You can do this by adding the following dependencies to your pom.xml file:

`
org.springframework.boot
spring-boot-starter-oauth2-client


org.springframework.security
spring-security-oauth2-jose
`

Configure OAuth 2.0

Next, configure OAuth 2.0 by creating a class that extends WebSecurityConfigurerAdapter. Here's an example:

`@Configuration
@EnableWebSecurity
public class SecurityConfig extends 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();
}
登录后复制

}`

This configuration allows anyone to access the /oauth2/, /login/, and /logout/** endpoints. All other endpoints require authentication. When a user logs in via OAuth 2.0, they will be redirected to the /home endpoint. When they log out, they will be redirected to the / endpoint.

Generate a Token

To generate a token, you can use the JwtBuilder class from the spring-security-oauth2-jose dependency. Here's an example:

`import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtBuilder;
import org.springframework.security.oauth2.jwt.Jwts;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.Date;

public class 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());
}
登录后复制

}`

This code generates a key pair, builds a JWT with the necessary claims, and signs it with the private key. The resulting token is printed to the console.

Note that this is just an example of how to generate a token. In practice, you would want to store the private key securely and use a different method of generating the expiration time.

Configure OAuth 2.0 Client

To use OAuth 2.0 in your application, you’ll need to configure a client. In Spring Boot, you can do this by adding properties to your application.properties file. Here's an example:

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 Boot的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板