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

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

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

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 {@Autowiredprivate AuthenticationManager authenticationManager;@Overridepublic 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");}@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {endpoints.authenticationManager(authenticationManager).tokenStore(tokenStore()).accessTokenConverter(accessTokenConverter());}@Beanpublic TokenStore tokenStore() {return new JwtTokenStore(accessTokenConverter());}@Beanpublic JwtAccessTokenConverter accessTokenConverter() {JwtAccessTokenConverter converter = new JwtAccessTokenConverter();converter.setSigningKey("signing-key");return converter;}
}

3. 配置资源服务器

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

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {@Overridepublic void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/public/**").permitAll().antMatchers("/api/**").authenticated();}@Overridepublic void configure(ResourceServerSecurityConfigurer resources) throws Exception {resources.resourceId("resource_id").tokenStore(tokenStore());}@Beanpublic TokenStore tokenStore() {return new JwtTokenStore(accessTokenConverter());}@Beanpublic 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 {@Overrideprotected 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-idclient-secret: your-client-secretscope: profile, emailredirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"authorization-grant-type: authorization_codeclient-name: Googleprovider:google:authorization-uri: https://accounts.google.com/o/oauth2/authtoken-uri: https://oauth2.googleapis.com/tokenuser-info-uri: https://www.googleapis.com/oauth2/v3/userinfouser-name-attribute: sub

6. 启用 HTTPS

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

server:ssl:key-store: classpath:keystore.p12key-store-password: changeitkey-store-type: PKCS12key-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.mzph.cn/news/852193.shtml

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

相关文章

HTML静态网页成品作业(HTML+CSS)—— 名人霍金介绍网页(6个页面)

&#x1f389;不定期分享源码&#xff0c;关注不丢失哦 文章目录 一、作品介绍二、作品演示三、代码目录四、网站代码HTML部分代码 五、源码获取 一、作品介绍 &#x1f3f7;️本套采用HTMLCSS&#xff0c;未使用Javacsript代码&#xff0c;共有6个页面。 二、作品演示 三、代…

vscode切换Python解释器

在vscode上切换解析器解决方案&#xff1a; 1、确认自己已经安装了python环境 2、command shift p ,在这里切换即可&#xff0c;见下图&#xff1a; 3、如果状态栏也就是右下角不现实切换操作的话&#xff0c;打开设置&#xff1a;

云时代的Java:在云环境中实施Java的最佳实践

引言 云计算已经成为现代软件开发不可或缺的一部分&#xff0c;它提供了灵活性、可扩展性和成本效益。对于Java开发者来说&#xff0c;掌握在云环境中部署和管理Java应用的最佳实践是至关重要的。本文将探讨一些关键策略&#xff0c;帮助你最大化Java在云平台上的性能和效率。…

阿里云aliyun cli的作用以及安装步骤

阿里云CLI&#xff08;Command Line Interface&#xff09;是一个命令行工具&#xff0c;它允许你使用命令行来管理和控制阿里云的服务。通过阿里云CLI&#xff0c;你可以创建和管理实例、存储、数据库等资源&#xff0c;而不需要通过阿里云的网页控制台。 以下是在Linux系统上…

【六】Linux安装部署Nginx web服务器--及编写服务器启动脚本

一、部署安装nginx 1、查看nginx是否安装依赖包 [rootlocalhost ~]# rpm -q zlib-devel pcre-devel package zlib-devel is not installed package pcre-devel is not installed 2、若没有则安装nginx 依赖包 [rootlocalhost ~]# yum -y install zlib-devel* pcre-dev…

2024.6.13 刷题总结

2024.6.13 **每日一题** 2813.子序列最大优雅度&#xff0c;本题利用了贪心的思想&#xff0c;首先将items按照profit从大到小进行排序&#xff0c;当子序列为前k个项目时&#xff0c;子序列的利润总和最大&#xff0c;但是总优雅度不一定最大&#xff0c;所以此时我们向后遍历…

01 Pytorch 基础

paddle不需要放数据到gpu&#xff01; 区别&#xff1a;1.batch_norlization 不同 2. 1.数据处理 1.取一个数据&#xff0c;以及计算大小 &#xff08;剩下的工作&#xff0c;取batch&#xff0c;pytorch会自动做好了&#xff09; 2.模型相关 如何得到结果 3.模型训练/模型…

6月13日 Qtday1

#include "mywidget.h" //腾讯会议的登录界面 MyWidget::MyWidget(QWidget *parent): QMainWindow(parent) {this->setFixedSize(468,830);//主窗口大小this->setStyleSheet("background-color:rgb(255,255,255)");//主窗口背景this->setWindowTi…

Oxlint 会取代 Eslint 吗?

最近&#xff0c;一个基于 Rust 的代码检查工具 Oxlint 在国外前端社区引起了热议&#xff0c;许多专家对其给予了高度评价。那么&#xff0c;相比于它的大哥 Eslint&#xff0c;Oxlint 有哪些优势&#xff1f;它会在未来取代 Eslint 吗&#xff1f;本文将讨论这个话题。 Oxc 和…

现货黄金投资价格怎么分析 低买高卖是核心!

我们做现货黄金投资&#xff0c;总是离不开对黄金价格的分析&#xff0c;分析其实就是一种理性的思考&#xff0c;我们对现货黄金当前走势进行一番思考&#xff0c;进而判断它未来的走向&#xff0c;以此作为自己投资入场的基础。那黄金投资价格怎么分析呢&#xff1f;下面我们…

Git 分支管理规范化[Git Flow ]分支管理策略

分支命名规范 master 分支&#xff1a;master 分支只有一个&#xff0c;名称即为 master。GitHub 现在叫 main develop 分支&#xff1a;develop 分支只有一个&#xff0c;名称即为 developfeature 分支&#xff1a;feature/<功能名>&#xff0c;例如&#xff1a;featu…

uniapp开发微信小程序预加载分包

微信小程序分包是一种优化小程序项目结构和性能的方式。它允许开发者将小程序代码包拆分成多个子包&#xff0c;在用户需要时动态加载这些子包&#xff0c;从而减少小程序的首次加载时间和主包的体积。&#xff08;总体积不得大于20M&#xff0c;主包&#xff08;共同文件静态资…

Matlab|基于主从博弈的智能小区代理商定价策略及电动汽车充电管理

目录 一、主要内容 二、部分代码 三、程序结果 四、下载链接 一、主要内容 主要做的是一个电动汽车充电管理和智能小区代理商动态定价的问题&#xff0c;将代理商和车主各自追求利益最大化建模为主从博弈&#xff0c;上层以代理商的充电电价作为优化变量&#xff0c;下层以…

从Android刷机包提取System和Framework

因为VIVO的手机很难解锁BL和Root&#xff0c;故直接从ADB中获取完整的Framework代码是比较困难的。我就考虑直接从VIVO提供的刷机包文件中获取相关的代码 由于vivo把system.new.dat分割了&#xff0c;所以下一步&#xff0c;我们使用cat命令&#xff0c;合并这些文件&#xff0…

Java I/O模型

引言 根据冯.诺依曼结构&#xff0c;计算机结构分为5个部分&#xff1a;运算器、控制器、存储器、输入设备、输出设备。 输入设备和输出设备都属于外部设备。网卡、硬盘这种既可以属于输入设备&#xff0c;也可以属于输出设备。 从计算机结构的视角来看&#xff0c;I/O描述了…

在 Kubernetes 上拉取 Harbor 私有仓库镜像并部署服务

上一篇讲解了IntelliJ IDEA和Jib Maven插件配合&#xff0c;镜像一键推送到Harbor私服仓库&#xff0c;今天来讲解下怎么让k8s直接拉取Harbor 私有仓库上面的镜像 创建 Kubernetes Secret 用于拉取镜像 因为 Harbor 仓库是私有的&#xff0c;我们需要创建一个 Kubernetes Sec…

JavaScript面向对象

一、编程思想 面向过程介绍 面向过程就是分析出解决问题所需要的步骤&#xff0c;然后用函数把这些一步一步实现&#xff0c;使用的时候再一个一个依次调用就可以了。 面向过程&#xff0c;就是按照我们分析好了的步骤&#xff0c;按照步骤解决问题。 面向对象编程&#xf…

使用Python实现管理员权限操作的WiFi的方法

在网络连接方面&#xff0c;无线局域网&#xff08;WLAN&#xff09;已成为我们日常生活中不可或缺的一部分&#xff1b;在某些情况下&#xff0c;我们可能需要管理员权限才能启用或禁用WLAN&#xff0c;但是通常会遇到权限不足的问题&#xff1b;为了解决这个问题&#xff0c;…

keil调试过程中遇到的问题及栈分析遇到的问题

文章目录 前言进行最坏运行时间分析及栈分析遇到的两个问题 一、问题1二、问题2总结 前言 进行最坏运行时间分析及栈分析遇到的两个问题 一、问题1 项目使用的时间片&#xff0c;在线调试过程中进行最坏运行时间通过打断点发现一个有个问题&#xff1a; 在一个时间片的开头和…

阻抗控制(Impedance Control)和导纳控制(Admittance Control)例子

阻抗控制(Impedance Control)和导纳控制(Admittance Control) 是两种用于机械臂或机器人交互控制的策略。阻抗控制定义的是机器人端部的力和位置之间的关系,而导纳控制则定义的是外力和运动之间的关系。导纳控制常用于处理机器人与环境交互中的力控制问题。 适用场景对比…