java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot OAuth2.0

SpringBoot集成OAuth2.0的实现示例

作者:珠峰日记

OAuth2.0是安全授权协议,通过访问令牌替代密码,保障用户数据安全,适用于社交登录、第三方数据访问等场景,下面就来介绍一下SpringBoot集成OAuth2.0,感兴趣的可以了解一下

OAuth 2.0 介绍

概念

OAuth 2.0 是一个开放标准的授权协议,它允许用户授权第三方应用访问其在另一个服务提供商处存储的受保护资源,而无需将自己的用户名和密码直接提供给第三方应用。这极大地增强了用户数据的安全性和隐私性,广泛应用于各种需要第三方授权访问的场景,如社交登录、第三方应用获取用户在云存储服务中的文件等。

与传统认证方式的对比

常见应用场景

OAuth 2.0 原理

核心角色

授权流程

OAuth 2.0 定义了四种授权模式,下面详细介绍最常用的授权码模式(Authorization Code Grant):

Spring Boot 集成 OAuth 2.0

1. 添加依赖

在 pom.xml 中添加以下依赖:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-client</artifactId>
    </dependency>
</dependencies>

2. 配置 OAuth 2.0 客户端

在 application.yml 中配置 OAuth 2.0 客户端信息,以 GitHub 为例:

spring:
  security:
    oauth2:
      client:
        registration:
          github:
            client-id: your-client-id
            client-secret: your-client-secret
            scope: read:user
        provider:
          github:
            authorization-uri: https://github.com/login/oauth/authorize
            token-uri: https://github.com/login/oauth/access_token
            user-info-uri: https://api.github.com/user

将 your-client-id 和 your-client-secret 替换为你在 GitHub 开发者设置中创建的实际客户端 ID 和客户端密钥。

3. 配置 Spring Security

创建一个配置类来配置 Spring Security 以支持 OAuth 2.0 登录:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
           .authorizeRequests()
               .anyRequest().authenticated()
               .and()
           .oauth2Login();
        return http.build();
    }
}

4. 创建控制器

创建一个简单的控制器来测试 OAuth 2.0 登录后的访问:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HomeController {

    @GetMapping("/")
    public String home() {
        return "Welcome to the protected area! You are authenticated.";
    }
}

5. 主应用类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootOauth2DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootOauth2DemoApplication.class, args);
    }
}

代码解释

按照上述步骤操作,就能在 Spring Boot 项目中集成 OAuth 2.0 认证。启动应用后,访问项目根路径,会自动跳转到 GitHub 的授权页面,授权成功后即可访问受保护的资源。

到此这篇关于SpringBoot集成OAuth2.0的实现示例的文章就介绍到这了,更多相关SpringBoot OAuth2.0内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文