Spring Security 与 JWT、OAuth 2.0 整合详解:构建安全可靠的认证与授权机制

news2025/6/28 5:15:15

Spring Security 与 OAuth 2.0 整合详解:构建安全可靠的认证与授权机制

将 JWT(JSON Web Token)与 OAuth 2.0 整合到 Spring Security 中可以为应用程序提供强大的认证和授权功能。以下是详细的整合步骤和代码示例。
CSDN开发云

1. 引入依赖

首先,确保在 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-oauth2-resource-server</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.security.oauth.boot</groupId>
    <artifactId>spring-security-oauth2-autoconfigure</artifactId>
    <version>2.5.4</version>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.9.1</version>
</dependency>

2. 配置授权服务器

首先,配置授权服务器以处理授权请求和颁发访问令牌。创建一个配置类来设置授权服务器:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
            .withClient("client_id")
            .secret("{noop}client_secret")
            .authorizedGrantTypes("authorization_code", "refresh_token", "password", "client_credentials")
            .scopes("read_profile", "write_profile")
            .redirectUris("https://client-app.com/callback");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
            .authenticationManager(authenticationManager)
            .tokenStore(tokenStore())
            .accessTokenConverter(accessTokenConverter());
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey("signing-key");
        return converter;
    }
}

3. 配置资源服务器

然后,配置资源服务器以保护资源并验证访问令牌:

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/public/**").permitAll()
                .antMatchers("/api/**").authenticated();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId("resource_id").tokenStore(tokenStore());
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey("signing-key");
        return converter;
    }
}

4. 配置客户端应用程序

接下来,配置客户端应用程序以请求授权码和访问令牌。创建一个配置类来设置客户端应用程序:

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Sso;

@Configuration
@EnableOAuth2Sso
public class OAuth2ClientConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/login").permitAll()
                .anyRequest().authenticated()
            .and()
            .oauth2Login()
                .loginPage("/login")
                .defaultSuccessUrl("/home", true);
    }
}

5. 配置应用程序属性

在 application.yml 或 application.properties 中配置 OAuth 2.0 客户端属性:

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
            client-name: Google
        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

6. 启用 HTTPS

OAuth 2.0 要求使用 HTTPS 来保护通信,因此,请确保您的应用程序配置了 HTTPS。以下是一个示例:

server:
  ssl:
    key-store: classpath:keystore.p12
    key-store-password: changeit
    key-store-type: PKCS12
    key-alias: tomcat

7. 启动应用程序

现在,您可以启动您的 Spring Boot 应用程序,并测试 OAuth 2.0 整合是否正常工作。尝试访问受保护的资源,并验证 OAuth 2.0 授权流程。

8. 测试 OAuth 2.0 授权流程

  • 访问未授权资源,浏览器将重定向到登录页面。
  • 选择 OAuth 2.0 提供者(例如 Google)。
  • 授权应用访问您的数据。
  • 重定向回应用并访问受保护的资源。

通过以上步骤,您已经成功地将 JWT 和 OAuth 2.0 整合到 Spring Security 中。这样,您的应用程序可以利用 OAuth 2.0 和 JWT 提供的强大功能进行身份验证和授权。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1822486.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【开源项目】重庆智慧城市案例~实景三维数字孪生城市CIM/BIM

飞渡科技数字孪生重庆管理平台&#xff0c;以实景三维平台为支撑&#xff0c;以城市数据库对接为核心&#xff0c;利用数字孪生技术&#xff0c;结合云计算、物联网IOT等技术&#xff0c;对接城市规划、智能交通、和公共安全等系统。 利用平台强大的国产自研渲染引擎&#xff0…

怎么压缩视频大小

在数字时代&#xff0c;视频已成为我们日常生活和工作中不可或缺的一部分。然而&#xff0c;视频文件的大小也越来越大&#xff0c;这给存储和传输带来了不小的挑战。因此&#xff0c;学会如何有效地压缩视频文件&#xff0c;就显得尤为重要。本文将详细介绍一种常用的视频压缩…

vscode中模糊搜索和替换

文章目录 调出搜索&#xff08;快捷键&#xff09;使用正则&#xff08;快捷键&#xff09;替换&#xff08;快捷键&#xff09;案例假设给定文本如下目标1&#xff1a;查找所有函数名目标2&#xff1a;替换所有函数名为hello目标3&#xff1a;给url增加查询字符串参数 调出搜索…

Coursera耶鲁大学金融课程:Financial Markets 笔记Week 01

Financial Markets 本文是学习 https://www.coursera.org/learn/financial-markets-global这门课的学习笔记 这门课的老师是耶鲁大学的Robert Shiller https://en.wikipedia.org/wiki/Robert_J._Shiller Robert James Shiller (born March 29, 1946)[4] is an American econ…

如何用Xcode创建你的第一个项目?学起来

前言 上一期&#xff0c;咱们已经有安装XCode的教程了。有小伙伴说建议跳过&#xff0c;嗯。。。如果你对开发很熟悉&#xff0c;那可以。但如果不熟悉&#xff0c;建议还是按照教程一步步来哦&#xff01; 毕竟统一了开发工具&#xff0c;咱们后续讲的内容学习起来也会简单一…

U-Mail反垃圾邮件网关助力企业抵御垃圾邮件,守护邮箱安全

在数字化时代&#xff0c;电子邮件已成为企业沟通不可或缺的工具&#xff0c;它在促进信息流通和提高工作效率方面扮演着关键角色。然而&#xff0c;随着电子邮件使用的普及&#xff0c;垃圾邮件问题也日益凸显&#xff0c;特别是那些携带恶意软件或钓鱼链接的邮件&#xff0c;…

2024 年最新 Python 调用 OpenAi 详细教程实现问答、图像合成、图像理解、语音合成、语音识别(详细教程)

OpenAi 环境安装 首先确保您的计算机上已经安装了 Python。您可以从 Python 官方网站下载并安装最新版本 Python。安装时&#xff0c;请确保勾选 “Add Python to PATH” &#xff08;添加环境变量&#xff09;选项&#xff0c;以便在 cmd 命令行中直接使用 Python。 安装 Op…

如何将ai集成到项目中,方法二

上一篇文章&#xff1a;如何将ai集成到radsystems项目中&#xff0c;在项目中引入ai-CSDN博客 上一篇文章内容主要针对于未实现权限分离的项目&#xff0c;这篇文章主要来说一下权限分离的项目怎么做&#xff0c;以及注意的细节。 一、编写前端router.js 二、编写前端askai.vu…

qemu microvm 测试运行记录

[v3] Introduce the microvm machine type | Patchew 下载获取rootfs wget http://dl-cdn.alpinelinux.org/alpine/v3.10/releases/x86_64/alpine-minirootfs-3.10.2-x86_64.tar.gz qemu-img create -f raw alpine-rootfs-x86_64.raw 1G losetup /dev/loop0 alpine-rootfs-x86…

服务器哪些因素会影响到网站SEO优化?

您是否曾想过&#xff0c;您的 SEO 性能下降&#xff0c;可能是网站服务器出了问题?鉴于此&#xff0c;在本文中&#xff0c;我们将探讨哪些服务器因素会影响您网站的 SEO&#xff0c;并提供可行的建议。 页面速度 搜索引擎非常看重您网站的加载速度。加载缓慢的网站会给用户体…

jenkins使用注意问题

1.在编写流水线时并不知道当前处在哪个目录&#xff0c;导致名使用不当&#xff0c;以及文件位置不清楚 流水线任务默认路径是&#xff0c;test4_mvn为jenkins任务名 [Pipeline] sh (hide)pwd /var/jenkins_home/workspace/test4_mvn maven任务也是&#xff0c;看来是一样的…

SY7304DBC 丝印VI DFN-10 33V,4A,1MHz升压稳压器芯片

在智能手机中&#xff0c;SY7304DBC 这类升压调节器可以有以下一些具体的使用案例&#xff1a; 1. 显示屏背光控制: 智能手机的显示屏背光需要一个稳定的电流来保持亮度均匀。SY7304DBC 可以在此应用场景中用于提供恒定的电流&#xff0c;确保屏幕清晰可见而不受电池电压波动的…

除了ps我们还可以使用什么方法来处理图片?

照片模糊了怎么办?当照片拍的不好时&#xff0c;容易出现模糊的状况&#xff0c;其实照片模糊了可以通过后期软件加工处理&#xff0c;但是ps操作很复杂&#xff0c;对我们有一定的技术基础要求&#xff0c;那么有没有别的图片处理工具呢&#xff1f; ps它的图片处理功能较为全…

【论文阅读笔记】LeSAM: Adapt Segment Anything Model for medical lesion segmentation

1.论文介绍 LeSAM: Adapt Segment Anything Model for medical lesion segmentation LeSAM&#xff1a;适用于医学病变分割的任意分割模型 2024年发表于 JBHI Paper 无code 2.摘要 Segment Anything Model&#xff0c;SAM是自然图像分割领域的一个基础性模型&#xff0c;取得…

计算机网络(6) TCP协议

TCP&#xff08;Transmission Control Protocol&#xff0c;传输控制协议&#xff09;是互联网协议套件中一种核心协议。它提供面向连接的、可靠的字节流传输服务&#xff0c;确保数据从一端正确无误地传输到另一端。TCP的主要特点包括&#xff1a; 可靠性&#xff1a;TCP使用…

怎么脚本ai创作?分享三个方法

怎么脚本ai创作&#xff1f;在数字化时代&#xff0c;AI技术正逐渐渗透到我们生活的方方面面&#xff0c;其中AI脚本创作软件的出现&#xff0c;极大地提高了创作效率&#xff0c;降低了创作门槛。今天&#xff0c;就为大家推荐三款备受好评的AI脚本创作软件&#xff0c;其中聪…

MyBatis 获取参数的两种方式

${paramName} 使用这种方式的结果是直接替换。 #{paramName} 使用这种方式的实现是占位符。&#xff08;?&#xff09;

昂辉科技EasySAR-BootLoader上位机产品

近年来&#xff0c;硬件标准化、同质化和软件差异化、复杂化成为了汽车产品研发的重要趋势。与此同时&#xff0c;大量的智能化功能和快速上车的节奏&#xff0c;对软件开发提出了更高的要求。在软硬件解耦的大背景下&#xff0c;建立统一的软件体系和开发工具以紧跟硬件更新迭…

UE4中性能优化工具合集

UE4中性能优化工具合集 简述CPUUnreal InsightUnreal ProfilerSimpleperfAndroid StudioPerfettoXCode TimeprofilerBest Practice GPUAdreno GPUMali GPUAndroid GPU Inspector (AGI) 内存堆内存分析Android StudioLoliProfilerUE5 Memory InsightsUnity Mono 内存MemreportRH…

JavaScript 基础 - 第2天【函数】

文章目录 前言一、声明和调用1、声明&#xff08;定义&#xff09;2、调用 二、参数三、返回值四、作用域1、全局作用域2、局部作用域 五、匿名函数1、函数表达式2、立即执行函数 前言 理解封装的意义&#xff0c;能够通过函数的声明实现逻辑的封装&#xff0c;知道对象数据类…