Spring Security OAuth2实现单点登录
1、概述
在本教程中,我们将讨论如何使用 Spring Security OAuth 和 Spring Boot 实现 SSO(单点登录)。
本示例将使用到三个独立应用
- 一个授权服务器(中央认证机制)
- 两个客户端应用(使用到了 SSO 的应用)
简而言之,当用户尝试访问客户端应用的安全页面时,他们首先通过身份验证服务器重定向进行身份验证。
我们将使用 OAuth2 中的 Authorization Code 授权类型来驱动授权。
2、客户端应用
先从客户端应用下手,使用 Spring Boot 来最小化配置:
2.1、Maven 依赖
首先,需要在 pom.xml 中添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
2.2、安全配置
接下来,最重要的部分就是客户端应用的安全配置:
@Configuration
@EnableOAuth2Sso
public class UiSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.antMatcher("/**")
.authorizeRequests()
.antMatchers("/", "/login**")
.permitAll()
.anyRequest()
.authenticated();
}
}
当然,该配置的核心部分是 @EnableOAuth2Sso 注解,我们用它来启用单点登录。
请注意,我们需要继承 WebSecurityConfigurerAdapter — 如果没有它,所有路径都将被保护 — 因此用户在尝试访问任何页面时将被重定向到登录页面。 在当前这个示例中,索引页面和登录页面可以在没有身份验证的情况下可以访问。
最后,我们还定义了一个 RequestContextListener bean 来处理请求。
application.yml:
server:
port: 8082
context-path: /ui
session:
cookie:
name: UISESSION
security:
basic:
enabled: false
oauth2:
client:
clientId: SampleClientId
clientSecret: secret
accessTokenUri: http://localhost:8081/auth/oauth/token
userAuthorizationUri: http://localhost:8081/auth/oauth/authorize
resource:
userInfoUri: http://localhost:8081/auth/user/me
spring:
thymeleaf:
cache: false
有几点需要说明:
- 我们禁用了默认的 Basic Authentication
accessTokenUri是获取访问令牌的 URIuserAuthorizationUri是用户将被重定向到的授权 URI- 用户端点
userInfoUriURI 用于获取当前用户的详细信息
另外需要注意,在本例中,我们使用了自己搭建的授权服务器,当然,我们也可以使用其他第三方提供商的授权服务器,例如 Facebook 或 GitHub。
2.3、前端
现在来看看客户端应用的前端配置。我们不想把太多时间花费在这里,主要是因为之前已经介绍过了。
客户端应用有一个非常简单的前端:
index.html:
<h1>Spring Security SSO</h1>
<a href="securedPage">Login</a>
securedPage.html:
<h1>Secured Page</h1>
Welcome, <span th:text="${#authentication.name}">Name</span>
securedPage.html 页面需要用户进行身份验证。 如果未经过身份验证的用户尝试访问 securedPage.html,他们将首先被重定向到登录页面。
3、认证服务器
现在让我们开始来讨论授权服务器。
3.1、Maven 依赖
首先,在 pom.xml 中定义依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
</dependency>
3.2、OAuth 配置
理解我们为什么要在这里将授权服务器和资源服务器作为一个单独的可部署单元一起运行这一点非常重要。
让我们从配置资源服务器开始探讨:
@SpringBootApplication
@EnableResourceServer
public class AuthorizationServerApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(AuthorizationServerApplication.class, args);
}
}
之后,配置授权服务器:
@Configuration
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("SampleClientId")
.secret("secret")
.authorizedGrantTypes("authorization_code")
.scopes("user_info")
.autoApprove(true) ;
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
}
需要注意的是我们使用 authorization_code 授权类型来开启一个简单的客户端。
3.3、安全配置
首先,我们将通过 application.properties 禁用默认的 Basic Authentication:
server.port=8081
server.context-path=/auth
security.basic.enabled=false
现在,让我们到配置定义一个简单的表单登录机制:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.requestMatchers()
.antMatchers("/login", "/oauth/authorize")
.and()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin().permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.parentAuthenticationManager(authenticationManager)
.inMemoryAuthentication()
.withUser("john").password("123").roles("USER");
}
}
请注意,虽然我们使用了简单的内存认证,但可以很简单地将其替换为自定义的 userDetailsService。
3.4、用户端点
最后,我们将创建之前在配置中使用到的用户端点:
@RestController
public class UserController {
@GetMapping("/user/me")
public Principal user(Principal principal) {
return principal;
}
}
用户数据将以 JSON 形式返回。
4、结论
在这篇快速教程中,我们使用 Spring Security Oauth2 和 Spring Boot 实现了单点登录。
一如既往,您可以在 GitHub 上找到完整的源码。
原文项目示例代码
本文转载自
原文作者:云栖路
原文链接:https://blog.csdn.net/s573626822/article/details/79870244
Spring Security OAuth2实现单点登录的更多相关文章
- Spring Security OAuth2 SSO 单点登录
基于 Spring Security OAuth2 SSO 单点登录系统 SSO简介 单点登录(英语:Single sign-on,缩写为 SSO),又译为单一签入,一种对于许多相互关连,但是又是各自 ...
- 【SpringSecurityOAuth2】源码分析@EnableOAuth2Sso在Spring Security OAuth2 SSO单点登录场景下的作用
目录 一.从Spring Security OAuth2官方文档了解@EnableOAuth2Sso作用 二.源码分析@EnableOAuth2Sso作用 @EnableOAuth2Client OA ...
- SpringCloud微服务实战——搭建企业级开发框架(四十):使用Spring Security OAuth2实现单点登录(SSO)系统
一.单点登录SSO介绍 目前每家企业或者平台都存在不止一套系统,由于历史原因每套系统采购于不同厂商,所以系统间都是相互独立的,都有自己的用户鉴权认证体系,当用户进行登录系统时,不得不记住每套系统的 ...
- springBoot整合spring security+JWT实现单点登录与权限管理--筑基中期
写在前面 在前一篇文章当中,我们介绍了springBoot整合spring security单体应用版,在这篇文章当中,我将介绍springBoot整合spring secury+JWT实现单点登录与 ...
- Spring Security安全以及单点登录
1.单点登录:多个系统,只需在一个系统登录以后,其他系统可以直接访问. 2.CAS(认证服务器),Apache Httpd,OpenLdap,OpenSSL(生成证书)几个工具实现 3.原理:登录通过 ...
- 【Spring Cloud & Alibaba 实战 | 总结篇】Spring Cloud Gateway + Spring Security OAuth2 + JWT 实现微服务统一认证授权和鉴权
一. 前言 hi,大家好~ 好久没更文了,期间主要致力于项目的功能升级和问题修复中,经过一年时间的打磨,[有来]终于迎来v2.0版本,相较于v1.x版本主要完善了OAuth2认证授权.鉴权的逻辑,结合 ...
- Spring Security Oauth2 单点登录案例实现和执行流程剖析
Spring Security Oauth2 OAuth是一个关于授权的开放网络标准,在全世界得到的广泛的应用,目前是2.0的版本.OAuth2在“客户端”与“服务提供商”之间,设置了一个授权层(au ...
- 使用Spring Security OAuth2进行简单的单点登录
1.概述 在本教程中,我们将讨论如何使用Spring Security OAuth和Spring Boot实现SSO - 单点登录. 我们将使用三个单独的应用程序: 授权服务器 - 这是中央身份验证机 ...
- Spring Security OAuth2 单点登录
1. OAuth 2.0 OAuth(Open Authorization)为用户资源的授权提供了一个安全的.开放而又简易的标准.最简单的理解,我们可以看一下微信OAuth2.0授权登录流程: 通过O ...
随机推荐
- winSocket编程(一)WSAStartup
/******************************************************************** 更新日期:2017-11-07 10:33:08* 进度:完 ...
- ( 递归 )Fractal -- POJ -- 2083
http://poj.org/problem?id=2083 Fractal Time Limit: 1000MS Memory Limit: 30000K Total Submissions: ...
- hdu 4920
http://acm.hdu.edu.cn/showproblem.php?pid=4920 给定两个n阶矩阵,求矩阵相乘后模3. 直接搞肯定会超时 特殊处理1和2的情况 实际上是水过的..... 貌 ...
- foreach控件的运用(非原创)http://blog.chinaunix.net/uid-26884465-id-3416869.html
人们对从认识事物都有一个具体到抽象的过程,学习Jmeter也不例外,通过一个实例来进行学习,一方面可以让初学者有所见即所得的信心,另一方面,其实也是在初学者心中留下了对这事物的一个朦胧的印象,这在以后 ...
- 封装了三个对TMemoryStream操作的函数,大牛莫笑
// TMemoryStream 转化为string字符串 function MemoryStreamToString(M: TMemoryStream): AnsiString; begin Set ...
- FastReport之实现打印固定行数,不足补打空白行的办法
在设置单据的打印模板的时候,我们有时候会遇到这样的情况:单据的内容很少,打印出来的效果不理想的情况,例如1.单据体与单尾之间有大量的空白: 2.单据体跟单尾连在一起,单尾后面的空白篇幅太大: 以上这两 ...
- hdu 1.2.5
#include<cstdio> #include<cstring> int main() { //freopen("input.txt","r& ...
- DFS遍历中forward、backward以及cross边的界定
再来看以下具体例子:
- artificial neural network in spark MLLib
神经网络模型 每个node包含两种操作:线性变换(仿射变换)和激发函数(activation function). 其中仿射变换是通用的,而激发函数可以很多种,如下图. MLLib中实现ANN 使用两 ...
- scrapy中Request中常用参数
url: 就是需要请求,并进行下一步处理的url callback: 指定该请求返回的Response,由那个函数来处理. method: 一般不需要指定,使用默认GET方法请求即可 headers: ...