首页 Java java教程 OAuth Spring Boot

OAuth Spring Boot

Sep 20, 2024 pm 06:17 PM

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中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

<🎜>:泡泡胶模拟器无穷大 - 如何获取和使用皇家钥匙
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系统,解释
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1664
14
CakePHP 教程
1423
52
Laravel 教程
1318
25
PHP教程
1268
29
C# 教程
1248
24
公司安全软件导致应用无法运行?如何排查和解决? 公司安全软件导致应用无法运行?如何排查和解决? Apr 19, 2025 pm 04:51 PM

公司安全软件导致部分应用无法正常运行的排查与解决方法许多公司为了保障内部网络安全,会部署安全软件。...

如何将姓名转换为数字以实现排序并保持群组中的一致性? 如何将姓名转换为数字以实现排序并保持群组中的一致性? Apr 19, 2025 pm 11:30 PM

将姓名转换为数字以实现排序的解决方案在许多应用场景中,用户可能需要在群组中进行排序,尤其是在一个用...

如何使用MapStruct简化系统对接中的字段映射问题? 如何使用MapStruct简化系统对接中的字段映射问题? Apr 19, 2025 pm 06:21 PM

系统对接中的字段映射处理在进行系统对接时,常常会遇到一个棘手的问题:如何将A系统的接口字段有效地映�...

IntelliJ IDEA是如何在不输出日志的情况下识别Spring Boot项目的端口号的? IntelliJ IDEA是如何在不输出日志的情况下识别Spring Boot项目的端口号的? Apr 19, 2025 pm 11:45 PM

在使用IntelliJIDEAUltimate版本启动Spring...

如何优雅地获取实体类变量名构建数据库查询条件? 如何优雅地获取实体类变量名构建数据库查询条件? Apr 19, 2025 pm 11:42 PM

在使用MyBatis-Plus或其他ORM框架进行数据库操作时,经常需要根据实体类的属性名构造查询条件。如果每次都手动...

Java对象如何安全地转换为数组? Java对象如何安全地转换为数组? Apr 19, 2025 pm 11:33 PM

Java对象与数组的转换:深入探讨强制类型转换的风险与正确方法很多Java初学者会遇到将一个对象转换成数组的�...

如何利用Redis缓存方案高效实现产品排行榜列表的需求? 如何利用Redis缓存方案高效实现产品排行榜列表的需求? Apr 19, 2025 pm 11:36 PM

Redis缓存方案如何实现产品排行榜列表的需求?在开发过程中,我们常常需要处理排行榜的需求,例如展示一个�...

电商平台SKU和SPU数据库设计:如何兼顾用户自定义属性和无属性商品? 电商平台SKU和SPU数据库设计:如何兼顾用户自定义属性和无属性商品? Apr 19, 2025 pm 11:27 PM

电商平台SKU和SPU表设计详解本文将探讨电商平台中SKU和SPU的数据库设计问题,特别是如何处理用户自定义销售属...

See all articles