Spring Security 自定义资源服务器实践

Spring Boot 2.x实战84 - Spring Security 8 - OAuth 2.0之Resource Server(基于JWT) OAuth 2.0是安全授权的工业标准协议,我们了解它需要理解下面的专用术语: 交互参与方: Client:需要访问Resource Sever受保护资源的应用; Resource Owner :终端用户,Client通过终端用户进行不同类型的授权(Grant Type); Authorization Server:提供访问授权的应用,Client使用某种Grant Type向Authorization Server获取Access Token; Resource Sever:包含受保护资源的应用, 阅读详情

安装资源服务器

1、 新建一个Spring Boot项目,命名为 spring-security-resource-server
2、引入pom.xml依赖

<pre class="prettyprint hljs xml" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, &quot;Courier New&quot;, monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;"><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>

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

其中与授权服务器依赖不同的是,资源服务器有spring boot版本,版本号会有spring boot进行管理,不需要显示声明。

配置资源服务器

1、配置application.yml 文件

<pre class="prettyprint hljs less" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, &quot;Courier New&quot;, monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: http://localhost:9000

该配置用于指定授权服务器地址,资源服务器将从该地址获取JWT令牌,并根据JWT中的属性进一步自我配置,发现授权服务器的公钥、验证JWT令牌。

2、创建配置类

<pre class="prettyprint hljs less" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, &quot;Courier New&quot;, monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">@EnableWebSecurity(debug = true)
public class ResoruceServerConfig { 

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { 
        http
                .authorizeRequests()
                .mvcMatchers("/userinfo/**").hasAuthority("SCOPE_userinfo")
                .and()
                .oauth2ResourceServer()
                .jwt();
        return http.build();
    }

}

.mvcMatchers("/userinfo/**").hasAuthority("SCOPE_userinfo") 匹配 /userinfo/** 地址,允许访问范围是 SCOPE_userinfo

oauth2ResourceServer() 定义为资源服务器

jwt() 使用JWT令牌

3、 创建一个资源接口

/userinfo/ 用来获取资源所有者基本信息

<pre class="prettyprint hljs kotlin" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, &quot;Courier New&quot;, monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">@Data
public class  UserInfoRes  { 

    private String username;
}

创建Rest接口

<pre class="prettyprint hljs kotlin" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, &quot;Courier New&quot;, monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">@RestController
public class  UserInfoController  { 

    @GetMapping("/userinfo")
    public UserInfoRes getUserInfo() { 
        UserInfoRes userInfoRes = new UserInfoRes();
        userInfoRes.setUsername("阿提说说");
        return userInfoRes;
    }
}

配置客户端

目前我们客户端的配置是这样的:

<pre class="prettyprint hljs less" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, &quot;Courier New&quot;, monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">spring:
  security:
    oauth2:
      client:
        registration:
          gitee:
            client-id: gitee_clientId
            client-secret: gitee_secret
            authorization-grant-type: authorization_code
            redirect-uri: '{baseUrl}/login/oauth2/code/{registrationId}'
            client-name: Gitee
          github:
            client-id: github_clientId
            client-secret: github_secret
          # 自定义
          customize:
            client-id: testClientId
            client-secret: testClientSecret
            authorization-grant-type: authorization_code
            redirect-uri: '{baseUrl}/login/oauth2/code/{registrationId}'
            client-name: Customize
            scope:
              - userinfo
        provider:
          gitee:
            authorization-uri: https://gitee.com/oauth/authorize
            token-uri: https://gitee.com/oauth/token
            user-info-uri: https://gitee.com/api/v5/user
            user-name-attribute: name
          # 自定义
          customize:
            authorization-uri: http://localhost:9000/oauth2/authorize
            token-uri: http://localhost:9000/oauth2/token
            user-info-uri: http://localhost:9000/userinfo
            user-name-attribute: username

这里我们只需要修改 customize 部分的 user-info-uri 和 user-name-attribute
调整后配置如下,其他部分跟原来是一样的。

<pre class="prettyprint hljs less" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, &quot;Courier New&quot;, monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">customize:
            authorization-uri: http://localhost:9000/oauth2/authorize
            token-uri: http://localhost:9000/oauth2/token
            user-info-uri: http://localhost:8090/userinfo
            user-name-attribute: username

:exclamation: user-name-attribute的名字,必须在user-info-uri返回的属性名中存在

整流程体验

在如上三部分配置完成后,就可以体验了,启动 spring-security-resource-server 、 spring-security-authorization-server 、 spring-security-oauth2-client

浏览器访问地址: http://127.0.0.1:8080/hello ,在授权完成后,即跳转回并显示结果。

ResourceServer下能看到带着token的 /userinfo 请求日志。

<pre class="prettyprint hljs markdown" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, &quot;Courier New&quot;, monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">************************************************************

Request received for GET '/userinfo':

org.apache.catalina.connector.RequestFacade@3418bfc9

servletPath:/userinfo
pathInfo:null
headers: 
accept: application/json
authorization: Bearer eyJraWQiOiI5YjZjZWMzNi05ZDYyLTRkMWMtOWRiNi0wMWM1ODQzMDc1N2UiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ1c2VyIiwiYXVkIjoidGVzdENsaWVudElkIiwibmJmIjoxNjYwOTU1ODQyLCJzY29wZSI6WyJ1c2VyaW5mbyJdLCJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3Q6OTAwMCIsImV4cCI6MTY2MDk1NjE0MiwiaWF0IjoxNjYwOTU1ODQyfQ.gVWwwfzB-xNuWWUBpgGokIOy5xwV9Wkd05k3rqpk1h92b-TWENB4ZArEL--zpngSyE8iuml0vG3veCv647FDx_EY56ClM-UxH-3Wq0D2f3b6WTgFO5RpCCwRLCHahBlV5g9plr7hWYY5uX2cQ4MsC4-ltZSR6wga5LSLDB-bIK46ZmJ3DOaQFwTTCpWB4OgOuq1j59i9XkgDUc_I8WUsHB4eEDEbBJeOmdimDn5O1Ux6nDhPgLMLcpnrt3lHLmXDTk8Q7hX7YBynO2VBm6wkTeYP4a2rfinfhW-LtF1o3hm8QAY0hn1QKSEeWU5K5qiIOVeSJ5FqrYJ_VQPadT1qAQ
user-agent: Java/11
host: localhost:8090
connection: keep-alive

Security filter chain: [
  DisableEncodeUrlFilter
  WebAsyncManagerIntegrationFilter
  SecurityContextPersistenceFilter
  HeaderWriterFilter
  CsrfFilter
  LogoutFilter
  BearerTokenAuthenticationFilter
  RequestCacheAwareFilter
  SecurityContextHolderAwareRequestFilter
  AnonymousAuthenticationFilter
  SessionManagementFilter
  ExceptionTranslationFilter
  FilterSecurityInterceptor
]

到此,我们通过自己搭建的授权服务器和资源服务器,完整体验了OAuth2流程。

在整个流程中,我们使用的是最严密的授权码模式,它将用户引导到授权服务器进行身份验证,授权服务器将发放的访问令牌传递给客户端,目前主流都是使用该模式, 因此特别重要,要好好体会 。

微服务-微服务Spring Security OAuth 2实战 OAuth 2.0 (Open Authorization)是一种开放标准的授权协议,允许用户授权第三方应用访问其在某个服务提供者上的受保护资源,而无需将其实际的凭证(如用户名和密码)分享给第三方应用。这种方式可以增加安全性,同时允许用户更好地控制其数据的访问权限。 阅读详情

相关推荐

Spring Security OAuth2 完全解析 (流程/原理/实战定制) —— Client / ResourceServer 篇

Python微信订餐小程序课程视频 https://edu.youkuaiyun.com/course/detail/36074 Python实战量化交易理财系统 https://edu.youkuaiyun.com/course/detail/35475 一、前言 本文假设读者对 Spring Security 本身原理有一定程度的了解,假设对 OAuth2 规范流程、Jwt 有基础了解,以此来对 SpringSecurity 整合 OAuth2 有个快速全面的认识。 (关于总体流程,若对SS实在不熟悉可以简单理解为:Filte

虚幻私塾 4638

oauth2-resource-server授权配置介绍

也就是授权(token中存放用户名、授权信息),接着资源服务器的token处理过程,可以直接请求授权服务器,由授权服务器验证;也可以在授权服务器确定固定的公钥私钥,资源服务器自己根据公钥解析token,获取jwt,最后获取用户信息。至此,资源服务器可以正常使用。若是你的系统比较庞大,每次请求都会请求授权服务器,这会给授权服务器带来压力,具体的实现方案可以根据实际情况而定。后,对授权服务器有一定的认识,那么授权服务器生成token后,该怎么用呢,这就涉及到资源服务器,现在给大家简单介绍实现过程。

言午玉口才 5016

使用Spring Security 资源服务器来保护Spring Cloud 微服务

是Spring Security的jose规范依赖。我将根据该类库来实现自定义的JWT解码器。/*** 基于Nimbus的jwt解码器,并增加了一些自定义校验策略*/@Bean// 从classpath路径读取cer公钥证书来配置解码器上面的解码器基于我们的公钥证书,同时我还自定义了一些校验策略。不得不说Nimbus的jwt类库比jjwt要好用的多。接下来配置资源服务器。

2401_89317793的博客 827

Spring OAuth2 Resource Server 配置

Spring OAuth2 Resource Server 是 Spring Security 中的一个模块,用于保护资源服务器上的API资源,确保只有持有合法访问令牌(access token)的客户端才能访问受保护的资源。

semicolon_hello的专栏 3471

【Spring Security】- part2

index:公共资源/hello: 受限资源@Bean```将默认配置进行扩展,要将默认配置覆盖。在上part有介绍过,实现默认配置的扩展,可以通过创建WebSecurityConfigurationAdapter或者SecurityFilterChain实现;

laufungjeoi的博客 154

Spring Boot Swagger UI报错“Unable to infer base url”排查与根治方案

在微服务架构和API开发中,API文档自动生成是提升开发效率的关键技术。其核心原理是通过扫描代码注解生成符合OpenAPI规范的JSON描述文件,再由前端UI动态渲染为可交互的文档界面。这项技术的价值在于实现代码与文档的同步更新,减少维护成本。在Spring Boot项目中,Springfox和Springdoc是实现该功能的常用库。然而,在实际工程实践中,开发者常遇到Swagger UI页面加载后报错“Unable to infer base url”的问题,这通常与**上下文路径(context-pat

weixin_30570101的博客 366

Spring Security 之密码存储

Spring Security的接口用于执行密码的单向转换,以便可以安全的存储密码。通常用于在认证时将用户提供的密码与存储的密码的比较。

分享技术干货和灵感、推荐新书和好玩的项目、分享Java面试题 1456

微服务安全实战:基于OAuth 2.1与Spring Authorization Server构建统一认证授权体系

在分布式微服务架构中,服务间安全通信与用户身份传递是核心挑战。传统的Session方案难以适应分布式环境,而简单的API Key则存在权限粒度粗、安全性低的问题。OAuth 2.0协议为此提供了标准化授权框架,其核心原理是通过引入授权服务器这一中心化角色,实现资源所有者、客户端与资源服务器之间的安全授权。OAuth 2.1作为其安全增强版本,强制要求使用PKCE机制来防范授权码注入攻击,并废弃了不安全的密码模式,显著提升了公共客户端场景下的安全性。这一技术方案在微服务、单页应用等现代架构中具有极高价值,能够

weixin_30568591的博客 345

Spring Security 之防漏洞攻击

了解CSRF攻击的最好方式是通过一个具体的例子。假设您的银行网站提供了一个转账页面,允许从当前的登录用户向另一个账户转账,转账单可能如下:Example 1. 转账表单

分享技术干货和灵感、推荐新书和好玩的项目、分享Java面试题 1851

基于Spring Security 6的OAuth2 系列之十四 - 资源服务器--自定义资源服务器

处理认证失败的异常:处理没有权限或者没有登录的异常我们从上一章知道资源服务器会去授权服务器请求得到JWT的公钥,或者配置某一个地方获取公钥。这里还有一种办法,就是本地公钥,可以通过自定义decoder方式,获取本地公钥,这样就可以不依赖其它服务。代码参考lesson08子模块1)新建lesson08子模块,复制和lesson07子模块一致2)在SecurityConfig配置下,配置自己加载本地的公钥@Beanhttp// userInfo接口需要SCOPE_profile权限。

代码让AI扣 1408

Spring Security OAuth2.0自定义资源服务核心配置——ResourceServer

目录 ResourceServerConfigurer ResourceServerConfigurerAdapter 插曲:WebSecurityConfigurerAdapter和ResourceServerConfigurerAdapter对比 实现ResourceServerConfigurerAdapter类重写方法自定义资源配置 上一篇写了授权服务器的配置,在Spring Security OAuth2.0可以把授权服务器(AuthorizationServer)和资源服务器(Reso

WannaRunning的博客 3238

Spring Security 之 JWT介绍

Json Web Token 简称JWT,是一个开放的行业标准(RFC 7519),它定义了一种简洁的、自包含的协议格式,用于在通信双方传递JSON对象,传递的信息经过数字签名可以被验证和信任。JWT可以使用HMAC算法或使用RSA的公钥/私钥来签名,防止被篡改。官网: https://jwt.io标准:https://tools.ietf.org/html/rfc7519JWT基于JSON,非常方便解析可以在令牌中自定义丰富的内容,易扩展。

分享技术干货和灵感、推荐新书和好玩的项目、分享Java面试题 2207

基于Spring Security 6的OAuth2 系列之十三 - 资源服务器--底层原理

7)得到的。

代码让AI扣 1292

spring boot security ajax_从零开始 -从Spring迁移到Spring Boot 这些点别忘记了 - 知识铺...

知识铺: 致力于打造轻知识点,持续更新每次的知识点较少,阅读不累。不占太多时间,不停地来唤醒你记忆深处的知识点。 1.概述 在本文中,将了解如何将现有的Spring Framework应用程序迁移到Spring Boot应用程序。 Spring Boot不是为了取代Spring,而是为了更快更容易地使用Spring。因此,迁移应用程序所需的大多数更改都与配置有关。 使用Spring Boot进...

weixin_39740283的博客 154

oauth2 spring-authorization-server自定义资源拥有者凭据许可模式

1.版本 spring-authorization-server 0.2.3 spring-boot 2.6.6 2.概述 spring-authorization-server中实现的oauth2标准中已经不支持自定义资源拥有者模式,但是项目从之前spring-seucirty-oauth2内置的升级到最新的授权服务器或者需要资源拥有者模式,就不要扩展 3.分析 官方源码的测试代码中给的示例初始化spring security的安全配置基本如下 protected void config

。。。。。。。 2207

平衡电桥在高压绝缘检测中的动态切换策略与误差优化

本文深入探讨了平衡电桥在高压绝缘检测中的动态切换策略与误差优化方法。通过分析四种基本切换模式及智能切换时序设计,显著提升检测精度与范围。结合电阻选型黄金法则和软件补偿技术,有效降低测量误差,为电动汽车电池管理系统提供可靠的安全保障。

weixin_30275415的博客 471

Spring Boot Starter Web:核心组件与自动配置解析

Spring Boot Starter Web是构建Java Web应用的基础依赖,它通过自动配置机制简化了Spring MVC框架的集成。自动配置是Spring Boot的核心特性,能够根据classpath中的依赖自动装配各种组件,如内嵌Tomcat服务器、JSON处理器和验证框架等。这种机制大幅提升了开发效率,使开发者能够快速搭建RESTful API和Web应用。在实际项目中,Spring Boot Starter Web常与Spring Security、MyBatis等框架配合使用,适用于微服务

weixin_33928137的博客 425

Windows下OpenMBEE项目MMS部署失败经历及改正

在Github里找到了上面的第一份文档,下载了MMS源代码(不知道为什么这个代码跟上面操作克隆得到的MMS代码不一样?好像是因为Gradle的版本问题,我本地之前已经安装过7.6.4的Gradle了,于是我找到gradle-wrapper.properties文件。后面在VScode中运行了一下依然是报这个错误,我在VScode终端直接执行。不知道为什么依然没什么用。打开“Windows PowerShell”。(如果是第一次运行它,将看到更长的输出)导航到要克隆存储库的文件夹,例如,

Yo_lan_da的博客 1868
上一篇: Java JNI 使用笔记
下一篇: 教你手撕分布式技术:(限流、通讯、缓存,)全部拿下
Java_ttcd
博客等级 码龄4年 198粉丝 190原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值