springboot oauth2学习(一)

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.resourceserver资源服务器配置,负责配置哪些url进行ouath2认证。通过继承ResourceServerConfigurerAdapter进行配置

2.AuthorizationServer授权服务器配置,负责关于token相关的配置。通过继承AuthorizationServerConfigurerAdapter进行配置

3.websecurity  web安全配置,负责配置用户的查询等安全相关的基本配置

对于用户认证,spirng oath2是依赖websecurity,即对于授权服务器必须要配置websecurity

根据使用场景不同,spring oauth2分成了4种模式

  • 授权码模式(authorization code)
  • 简化模式(implicit)
  • 密码模式(resource owner password credentials)
  • 客户端模式(client credentials)

项目环境依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>

配置资源服务器

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.requestMatchers().anyRequest().and()
                .authorizeRequests()
                .antMatchers("/getuser").permitAll()
                .antMatchers("/adduser").authenticated();
    }

}

/getuser不需要进行认证,/adduser需要认证

webscurity配置

import org.springframework.context.annotation.Bean;
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.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable().requestMatchers().anyRequest().and().authorizeRequests()
                .antMatchers("/getuser").authenticated()
                .antMatchers("/adduser").authenticated()
                .and()
                .formLogin();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        AuthenticationManager authenticationManager = super.authenticationManagerBean();
        return authenticationManager;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(getUserDetailService());
    }

    public UserDetailsService getUserDetailService() {
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("user_1").password(new BCryptPasswordEncoder().encode("123456")).authorities("USER").build());
        manager.createUser(User.withUsername("user_2").password(new BCryptPasswordEncoder().encode("123456")).authorities("USER").build());
        return manager;
    }
    
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}

/getuser、/adduser都配置为需要认证,但是不会生效,因为上面ResourceServerConfig 优先级高于webscurity。其实websecurity与ResourceServerConfig配置应该相互补充,即ResourceServerConfig没有控制的url可以用webscurity进行补充控制。

@Bean PasswordEncoder配置起到覆盖默认的DelegatingPasswordEncoder,就不会出现There is no PasswordEncoder mapped for the id "null"错误了。如果需要明文校验密码自己实现PasswordEncoder接口即可。

getUserDetailService提供了内存用户,也可以修改为查数据库。

授权服务器配置

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
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.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
    @Autowired
    AuthenticationManager authenticationManager;
    @Autowired
    RedisConnectionFactory redisConnectionFactory;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        //配置两个客户端,一个用于password认证一个用于client认证
        clients.inMemory().withClient("client_1")
                .authorizedGrantTypes("client_credentials", "refresh_token")
                .scopes("select")
                .authorities("client")
                .secret(new BCryptPasswordEncoder().encode("a123a"))
                .and().withClient("client_2")
                .authorizedGrantTypes("password", "refresh_token")
                .scopes("select")
                .authorities("client")
                .secret(new BCryptPasswordEncoder().encode("b123b"));
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

        endpoints.tokenStore(new RedisTokenStore(redisConnectionFactory))
                .authenticationManager(authenticationManager)
                .allowedTokenEndpointRequestMethods(HttpMethod.GET);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()")
                .allowFormAuthenticationForClients();
    }
}

注意allowFormAuthenticationForClients()这个配置,如果有这个配置获取token等走表单请求处理逻辑,不走基于basic的逻辑。

不配置allowFormAuthenticationForClients(),用浏览器访问/oauth/token会弹出basic认证的输入框,用postman访问/oauth/token会直接返回401没有权限

参考:https://blog.csdn.net/u013887008/article/details/82425805

不配置allowFormAuthenticationForClients(),走basic时,获取token过程原理参考:

https://my.oschina.net/u/2518341/blog/3020109

配置allowFormAuthenticationForClients(),获取token过程原理参考:

https://blog.csdn.net/u013815546/article/details/76977239

 

resourceserver和websecurity

1.资源服务器配置与websecurity配置都有http的配置

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable().requestMatchers().anyRequest().and().authorizeRequests()
                .antMatchers("/getuser").authenticated()
                .antMatchers("/adduser").authenticated()
                .and()
                .formLogin();
    }
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.requestMatchers().anyRequest().and()
                .authorizeRequests()
                .antMatchers("/getuser").permitAll()
                .antMatchers("/adduser").authenticated();
    }

对于/getuser上面的配置一个是permitAll() 另个一个是authenticated(),此时ResourceServerConfig 中配置的permitAll()生效。因为ResourceServerConfigurerAdapter 优先级高于WebSecurityConfigurerAdapter 。ResourceServerConfigurerAdapter 的过滤器顺序值是3,WebSecurityConfigurerAdapter的过滤器顺序值是100。

 优先级分析参考:https://blog.csdn.net/yaomingyang/article/details/97481892

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

相关推荐

springboot整合oauth2

springboot整合oauth2.0 文章目录springboot整合oauth2.01.概念2.springboot整合oauth2.0示例2.1SecurityConfig配置2.2资源服务器配置和授权服务器配置3.测试 环境 springboot1.5.x demo下载: 1.概念 客户应用: 通常是一个web或者手机,他需要访问用户的受保护资源 资源服务器::是一个web站点或者w...

2010yhh 2万+

Spring Security Oauth2 ResourceServerConfigurerAdapter (资源服务器配置)

ResourceServerConfigurerAdapter (资源服务器配置) 内部关联了ResourceServerSecurityConfigurer 和 HttpSecurity。前者与资源安全配置相关,后者与http安全配置相关 @Override public void configure(ResourceServerSecurityConfigurer resources) { //resourceId 用于分配给可授予的clientId

wangooo的博客 1万+

SpringBoot OAuth2自定义登陆/授权页

SpringBoot+Oauth2自定义登陆页和授权页的两种实现方式。

m0_60681411的博客 2687

ResourceServerConfigurerAdapter与WebSecurityConfigurerAdapter同时使用只有ResourceServerConfigurerAdapter生效

1.此处使用的ResourceServerConfigurerAdapter是spring-security-oauth2中的,WebSecurityConfigurerAdapter是spring-security-config中的; 2.同时使用上面的两种配置的时候,如果两者配种存在重写相同的方法时,后者的会出现配置不生效的问题,比如重写了configure这个方法(参数final不影响) 3.造成这个问题的主要原因其实就是因为两者的默认自动注册的@Order的优先级不同(具体情况请自行参考源码

l244112311的博客 6733

Springboot实现OAuth2登录

初涉认证,觉得Spring Securty好神奇,注册几个接口,就可以完成认证和授权。本次的目标是实现OAuth2的登录。 OAuth2登录,依赖 Spring Security 5.0 。SpringBoot 2.0 中已经整合。 1. 引入依赖 首先,需要引入Spring Security相关的依赖: &amp;lt;dependency&amp;gt; &amp;lt;groupId&amp;gt;org....

发财哥的笔记 1万+

SpringBoot+SpringSecurity OAuth2 认证服务搭建实战 (一)

配置:Maven,SpringBoot3.3.0,Spring-Security-oauth2-authorization-server 1.3.0(这个在pom中是用starter代替掉了),最后是JDK17,当然jdk版本不是必须的,其它版本也是可以的,只要别太低。作者当前用的SpringBoot是3.3.0的,算是比较新的版本,在这个版本的依赖列表中,Spring Authorization Server的版本是1.3.0。这里非常确定的告诉大家,资源服务器的代码和授权服务代码是写在一个项目中的。

2499

SpringBoot整合OAuth2

1. OAuth2.0介绍 OAuth(开放授权)是一个开放标准,允许用户授权第三方应用访问他们存储在另外的服务提供者上的信息,而不需要将用户名和密码提供给第三方应用或分享他们数据的所有内容。OAuth2.0是OAuth协议的延续版本,但不向后兼容OAuth 1.0即完全废止了OAuth1.0。很多大公司如Google,Yahoo,Microsoft等都提供了OAUTH认证服务,这些都足以说明OAUTH标准逐渐成为开放资源授权的标准。Oauth协议目前发展到2.0版本,1.0版本过于复杂,2.0版本已得到

明平姚的博客 1万+

SpringBoot学习笔记(十五:OAuth2 )

《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》,点击传送门,即可获取!{“access_token”:“ACCESS_TOKEN”,“token_type”:“bearer”,“expires_in”:2592000,“refresh_token”:“REFRESH_TOKEN”,“scope”:“read”,“uid”:100101,“info”:{…}}上面 JSON 数据中,access_token字段就是令牌,A 网站在后端拿到了。有些 Web 应用是纯前端应用,没有后

2401_84093490的博客 1749

SpringBoot OAuth2.0认证管理流程详解

OAuth2.0是一个开放的授权协议,可以用来实现第三方应用对我们API的访问控制,OAuth2.0中定义的角色包括: 1) Resource Owner(资源拥有者) 2) Client (第三方接入平台,请求者) 3) Resource Server (服务器资源: 数据中心) 4) Authorization Server (认证服务器) 授权认证的基本流程包括: 首先Client需要向Resource Ow......

u012477420的博客 1万+

springboot整合oauth2(一)

项目背景:win10,Intellij IDEA, java11 官方地址:https://docs.spring.io/spring-boot/docs/2.1.6.RELEASE/reference/html/boot-features-security.html#boot-features-security-oauth2 https://www.oauth.com/ GitHub地址:...

zsx18273117003的博客 2855

springboot集成oauth2报错

参照官方文档:https://spring.io/guides/tutorials/spring-boot-oauth2/#_social_login_simple 引入的项目依赖: <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot...

zsx18273117003的博客 2503

springboot2整合oauth2

1.背景 项目由springboot1.5.X升级到springboot2.0.0后,导致各组件API以及依赖包发生了变化。 完整项目demo:https://gitee.com/zkane/springboot2-oauth2.git 2.spring security Spring Security 从入门到进阶系列教程网址:http://www.spring4all.com/ar...

qq_37170583的博客 6万+

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

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

WannaRunning的博客 3242

SpringBoot搭建OAuth2

本文描述了通过SpringBoot从无到有的搭建OAuth2服务器的一系列实践过程。其中包括OAuth2的授权方式介绍,测试场景,过程中遇到的困难等,对新接触OAuth2的人有较大帮助。

m0_60681411的博客 3693

自然语言处理:稀疏向量表示

稀疏向量表示是指运用特定的方法和技术,将数据(如文本、图像、信号等)转化为向量形式,且该向量具有大部分元素值为零,仅少数元素值非零的特征,以此来实现对数据的高效存储、处理和分析。

老赵爱学习的博客 1449

我的AI学习 ai维护工具之langfuse

as_type: Optional[Literal[‘generation’]] = None, # 将记录定义为 Observation (LLM 调用)transform_to_string: Optional[Callable[[Iterable], str]] = None # 将输出转为 string。要用LangFuse的云服务,首先要在LangFuse官网上注册,注册完后将页面拉倒最后,点免费的SignUp,API文档:https://api.reference.langfuse.com/

liubaobin的博客 4102

SpringBoot集成OAuth2

1.背景介绍 1. 背景介绍 OAuth2 是一种授权协议,允许用户授权第三方应用程序访问他们的资源。它是一种“授权”模式,而不是“认证”模式。OAuth2 的主要目的是允许用户授权第三方应用程序访问他们的资源,而不需要将他们的凭据(如用户名和密码)传递给第三方应用程序。 Spring Boot 是一个用于构建新 Spring 应用程序的开箱即用的 Spring 框架。它旨在简化开发人员的工...

AI天才研究院 1586

从零开始写一个RTSP服务器(一)RTSP协议讲解

从零开始写一个RTSP服务器系列 从零开始写一个RTSP服务器(一)不一样的RTSP协议讲解 从零开始写一个RTSP服务器(二)RTP传输H.264(待写) 从零开始写一个RTSP服务器(三)一个传输H.264的RTSP服务器(待写) 从零开始写一个RTSP服务器(四)RTP传输AAC(待写) 从零开始写一个RTSP服务器(五)一个传输AAC的RTSP服务器(待写) 从零开始写一个RTSP服务器(...

JT同学的博客 7万+

OAuth2学习(二)——OAuth2实战

在上一篇文章中我们讲解了OAuth2的一些基本概念,对OAuth2有了基本的认识。这一节内容我们就讲解一下OAuth2实战,围绕

Anumbrella 7194

AT89C52单片机+LCD屏:手把手教你做一个能算小数和负数的计算器(附完整代码)

本文详细介绍了如何使用AT89C52单片机和LCD1602显示屏构建一个支持小数和负数运算的高精度计算器。从硬件选型、系统架构设计到核心算法实现,提供了完整的代码示例和优化技巧,特别适合51单片机初学者和课程设计参考。

weixin_30374009的博客 374

Linux vcan虚拟CAN接口配置与实战:从内核模块到自动化测试

CAN总线是嵌入式与汽车电子领域的基础通信协议,SocketCAN作为Linux内核原生支持,提供了标准化的CAN接口抽象。vcan虚拟CAN接口基于SocketCAN实现,通过纯软件模拟CAN网络设备,无需物理硬件即可完成报文收发与协议验证。其技术价值在于降低开发测试成本,支持多节点通信模拟、压力测试与CI集成。典型应用场景包括CANopen、J1939、UDS诊断协议开发,以及自动化回归测试。本文详细介绍了vcan内核模块加载、接口创建、参数配置、can-utils工具集使用及Python脚本通信,并涵

weixin_42709044的博客 207

SpringBoot集成SpringSecurity5和OAuth2 — 5、OAuth2集成JWT

SpringBoot集成SpringSecurity5和OAuth2 — 5、OAuth2集成JWT

Mr_XiMu的博客 3120

希捷硬盘卡死修复实战:U盘启动盘制作与低格清零全流程

机械硬盘使用多年后常出现卡顿、假死、坏道等问题,很多用户在网上搜索“希捷硬盘低格工具”或“U盘硬盘复活器”,却发现要么工具不明,要么操作不当造成二次损伤。其实所谓修复工具,本质是U盘启动环境配合硬盘检测与清零软件,低格并非修复物理坏道,而是通过全盘写零触发主控重映射,隔离不稳定扇区。懂原理后,用官方SeaTools、Ventoy/U盘启动盘、Victoria或Linux dd等组合工具,即可对可抢救的硬盘做清零修复。这一技术适用于逻辑坏道、SMART警告、扇区不稳定等场景,但需先备份数据并判断盘体是否有异响

weixin_30431445的博客 225
上一篇: springboot自动配置redis原理
下一篇: oauth2资源服务与认证服务分离
join_null
博客等级 码龄11年 25粉丝 113原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址