首页 > 其他分享 >在Spring Boot中实现OAuth2.0认证

在Spring Boot中实现OAuth2.0认证

时间:2024-07-20 15:55:15浏览次数:6  
标签:web Spring Boot springframework org import OAuth2.0

在Spring Boot中实现OAuth2.0认证

大家好,我是微赚淘客系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!

OAuth2.0 是一种用于授权的协议,它使得用户可以授权第三方应用程序访问他们在某服务提供商上的资源,而无需共享他们的凭据。Spring Boot 提供了对 OAuth2.0 的原生支持,可以方便地将其集成到应用程序中。本文将详细介绍如何在 Spring Boot 中实现 OAuth2.0 认证。

1. 创建 Spring Boot 项目

首先,我们需要创建一个 Spring Boot 项目,并添加所需的依赖项。在 pom.xml 中添加以下依赖:

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

2. 配置 OAuth2.0 客户端

application.yml 文件中配置 OAuth2.0 客户端信息。假设我们要集成 Google 作为认证提供者:

spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: your-client-id
            client-secret: your-client-secret
            scope: profile, email
            redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
            authorization-grant-type: authorization_code
        provider:
          google:
            authorization-uri: https://accounts.google.com/o/oauth2/auth
            token-uri: https://oauth2.googleapis.com/token
            user-info-uri: https://www.googleapis.com/oauth2/v3/userinfo
            user-name-attribute: sub

在这个配置中,client-idclient-secret 是在 Google API 控制台中创建 OAuth2.0 客户端时获得的。redirect-uri 是用户授权后 Google 重定向到的 URI。

3. 创建安全配置

创建一个配置类来设置 Spring Security 的 OAuth2.0 认证:

package cn.juwatech.config;

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.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/login**").permitAll()
                .anyRequest().authenticated()
                .and()
            .oauth2Login()
                .defaultSuccessURL("/home", true)
                .failureUrl("/login?error")
                .and()
            .logout()
                .logoutSuccessUrl("/");
    }
    
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http
                .authorizeRequests(authorizeRequests ->
                    authorizeRequests
                        .antMatchers("/", "/login**").permitAll()
                        .anyRequest().authenticated()
                )
                .oauth2Login(withDefaults())
                .build();
    }
}

在这个配置中,oauth2Login() 方法启用 OAuth2.0 登录,并配置了登录成功和失败的重定向 URL。所有请求都要求用户经过身份验证,除非访问根路径或登录路径。

4. 创建控制器

创建一个简单的控制器来处理应用的主页面和登录成功后的页面:

package cn.juwatech.controller;

import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MainController {

    @RequestMapping("/")
    public String index() {
        return "index";
    }

    @GetMapping("/home")
    @ResponseBody
    public String home(Authentication authentication) {
        return "Welcome, " + authentication.getName();
    }
}

/home 路径是用户登录成功后的重定向地址,authentication.getName() 可以获取当前登录用户的信息。

5. 创建视图

src/main/resources/templates 目录下创建 index.htmlhome.html 文件,用于展示应用的主页和用户信息页面。以下是 index.html 的示例:

<!DOCTYPE html>
<html>
<head>
    <title>OAuth2.0 Login</title>
</head>
<body>
    <h1>Welcome to the OAuth2.0 Demo</h1>
    <a href="/oauth2/authorization/google">Login with Google</a>
</body>
</html>

在这个视图中,我们创建了一个登录链接,当用户点击时会重定向到 Google 的登录页面。

6. 运行与测试

现在,可以运行 Spring Boot 应用程序,并在浏览器中访问 http://localhost:8080。点击 "Login with Google" 链接将重定向到 Google 登录页面。成功登录后,用户将被重定向到 /home 路径,显示欢迎信息。

7. 总结

通过以上步骤,我们在 Spring Boot 中成功实现了 OAuth2.0 认证。配置 OAuth2.0 客户端、设置 Spring Security 的 OAuth2.0 配置、创建控制器和视图都是实现这一认证流程的关键步骤。使用 Spring Boot 和 OAuth2.0,可以轻松实现安全的用户认证和授权功能。

本文著作权归聚娃科技微赚淘客系统开发者团队,转载请注明出处!

标签:web,Spring,Boot,springframework,org,import,OAuth2.0
From: https://www.cnblogs.com/szk123456/p/18313201

相关文章

  • 在Spring Boot中实现WebSocket实时通信
    在SpringBoot中实现WebSocket实时通信大家好,我是微赚淘客系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!在现代web应用中,实时通信功能越来越受到重视。WebSocket协议是一种在单个TCP连接上进行全双工通信的协议,允许客户端和服务器之间进行实时数据传输。SpringBoot......
  • 使用Java和Spring MVC构建Web应用
    使用Java和SpringMVC构建Web应用大家好,我是微赚淘客系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!在现代企业中,Web应用程序是最常见的应用类型之一。SpringMVC是一个强大且流行的JavaWeb框架,用于构建功能强大且易于维护的Web应用程序。本文将通过实际示例展示如......
  • Spring Boot+WebSocket向前端推送消息
     ​ 博客主页:   南来_北往......
  • Springboot 启动时Bean的创建与注入(二)-面试热点-springboot源码解读-xunznux
    Springboot启动时Bean的创建与注入,以及对应的源码解读文章目录Springboot启动时Bean的创建与注入,以及对应的源码解读11、getBean:200,AbstractBeanFactory(org.springframework.beans.factory.support)12、doGetBean:335,AbstractBeanFactory(org.springframework......
  • java项目(knife4j使用,静态资源未放在static资源包下,公共字段自动填充,Spring Cache与Spr
    Knife4j(生成接口文档)使用swagger你只需要按照它的规范去定义接口及接口相关的信息,就可以做到生成接口文档,以及在线接口调试页面。官网:https://swagger.io/Knife4j是为JavaMVC框架集成Swagger生成Api文档的增强解决方案。使用方式1、导入knife4j的maven坐标<dependency>......
  • 观察者模式实战:Spring Boot中联动更新机制的优雅实现
    引言在许多应用系统中,我们经常需要处理多个表之间的关联更新问题。例如,在教育管理系统中,当学生的基本信息表中的年龄字段发生更改时,我们可能还需要同步更新学生档案表和学生成绩表中的相关信息。本文将通过一个具体的案例,介绍如何在SpringBoot项目中利用观察者模式来优雅地解......
  • Spring cloud 安全部署与性能优化
    Mr.NeoChen(陈景峯),netkiller,BG7NYT节选自《NetkillerSpringCloud手札》多维度架构-知乎​www.zhihu.com/club/1241768772601950208​编辑1.环境安装1.1.操作系统初始化操作系统按完成后,使用下面脚本做一次初始化curl-shttps://raw.githubusercontent.co......
  • SpringBoot+Vue的闲一品零食交易平台(前后端分离)
    技术栈JavaSpringBootMavenMySQLmybatisVueShiroElement-UI角色对应功能网站用户管理员项目功能截图......
  • SpringBoot+Vue的进存销管理系统(前后端分离)
    技术栈JavaSpringBootMavenMySQLmybatisVueShiroElement-UI角色对应功能管理员员工项目功能截图......
  • 基于Java Springboot餐厅点餐系统
    作者介绍:✌全网粉丝10W+本平台特邀作者、博客专家、CSDN新星计划导师、软件领域优质创作者,博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于项目实战✌一、作品包含源码+数据库+设计文档万字+全套环境和工具资源+部署教程二、项目技术前端技术:Html、Css......