温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring Security整合Oauth2实现流程详解

发布时间:2020-10-12 07:48:15 来源:脚本之家 阅读:243 作者:鼓捣猫腻 栏目:开发技术

一、创建项目并导入依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth3</artifactId>
<version>2.3.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

注:这里的oauth3不是springboot那个,这是springsecurity。

Oauth3一共有四种认证模式是

本篇是password的认证模式,用于前后端分离登陆

第三方登陆一般是授权码模式

二、相关配置和代码

注:授权服务器和资源服务器一般是分开来的,我这里就不分开了

2.1)application.properties

spring.redis.host=192.168.21.135

spring.redis.port=6379

spring.redis.database=0

spring.redis.password=520hufei520

2.2)创建授权服务

2.2.1)实现AuthorizationServiceConfigurerAdapter

Spring Security整合Oauth2实现流程详解

@Configuration表示这个一个配置类

@EnableAuthorizationServer表示开启授权服务

2.2.2)注入AuthenticationManager、RedisConnectionFactory、UserDetailsService

Spring Security整合Oauth2实现流程详解

AuthenticationManager表示支持password认证模式

RedisConnectionFactory登陆成功后的token需要存在redis里面,因为redis里面有过期机制

UserDetailsService里面存放着用户信息

2.2.3)重写方法

Spring Security整合Oauth2实现流程详解

Spring Security整合Oauth2实现流程详解

2.3)创建资源服务

2.3.1)实现ResourceServerConfigurerAdapter

Spring Security整合Oauth2实现流程详解

@configuration表示这是一个配置类

@enbaleResourceServer表示开启资源服务

2.3.2)重写方法

Spring Security整合Oauth2实现流程详解

2.4)创建Security配置类

2.4.1)实现WebSecurityConfigurerAdapter

Spring Security整合Oauth2实现流程详解

2.4.2)将授权服务需要的两个bean,提供给它

Spring Security整合Oauth2实现流程详解

Spring Security整合Oauth2实现流程详解

@Bean表示告诉方法,产生一个Bean对象,然后这个Bean对象交给Spring管理。产生这个Bean对象的方法Spring只会调用一次,随后这个Spring将会将这个Bean对象放在自己的IOC容器中。

@Bean和@Component作用一样都是将bean注册到spring容器中去

2.4.3)重写方法

Spring Security整合Oauth2实现流程详解

2.5)创建Controller

Spring Security整合Oauth2实现流程详解

三、测试&效果

3.1)获取访问资源服务的token

Spring Security整合Oauth2实现流程详解

3.2)访问资源服务

Spring Security整合Oauth2实现流程详解

3.3)刷新token

Spring Security整合Oauth2实现流程详解

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI