使用Spring Security OAuth2实现单点登录

作者:程序猿Knight 时间:2023-08-13 01:44:34 

1.概述

在本教程中,我们将讨论如何使用Spring Security OAuth和Spring Boot实现SSO - 单点登录。

我们将使用三个单独的应用程序:

•授权服务器 - 这是中央身份验证机制
•两个客户端应用程序:使用SSO的应用程序

非常简单地说,当用户试图访问客户端应用程序中的安全页面时,他们将被重定向到首先通过身份验证服务器进行身份验证。

我们将使用OAuth2中的授权代码授权类型来驱动身份验证委派。

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.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.0.1.RELEASE</version>
</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。Security配置

接下来,最重要的部分,我们的客户端应用程序的Security配置:


@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
servlet:
 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

一些快速说明:

•我们禁用了默认的基本身份验证
•accessTokenUri是获取访问令牌的URI
•userAuthorizationUri是用户将被重定向到的授权URI
•userInfoUri用户端点的URI,用于获取当前用户详细信息

另请注意,在我们的示例中,我们推出了授权服务器,但当然我们也可以使用其他第三方提供商,如Facebook或GitHub。

2.3。前端

现在,让我们来看看客户端应用程序的前端配置。我们不会在这里专注于此,主要是因为我们已经在网站上介绍过。
 我们的客户端应用程序有一个非常简单的前端;这是index.html:


<h1>Spring Security SSO</h1>
<a href="securedPage" rel="external nofollow" >Login</a>

和securedPage.html:


<h1>Secured Page</h1>
Welcome, <span th:text="${#authentication.name}">Name</span>

securedPage.html页面需要对用户进行身份验证。如果未经身份验证的用户尝试访问securedPage.html,则会首先将其重定向到登录页面。

3. Auth服务器

现在让我们在这里讨论我们的授权服务器。

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>
<version>2.3.3.RELEASE</version>
</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 BCryptPasswordEncoder passwordEncoder;
@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(passwordEncoder.encode("secret"))
  .authorizedGrantTypes("authorization_code")
  .scopes("user_info")
  .autoApprove(true)
  .redirectUris("http://localhost:8082/ui/login","http://localhost:8083/ui2/login");
}
}

请注意我们如何仅使用authorization_code grant类型启用简单客户端。

另外,请注意autoApprove如何设置为true,以便我们不会被重定向并手动批准任何范围。

3.3。Security配置

首先,我们将通过application.properties禁用默认的基本身份验证:


server.port=8081
server.servlet.context-path=/auth

现在,让我们转到配置并定义一个简单的表单登录机制:


@Configuration
@Order(1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@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.inMemoryAuthentication()
  .withUser("john")
  .password(passwordEncoder().encode("123"))
  .roles("USER");
}
@Bean
public BCryptPasswordEncoder passwordEncoder(){
 return new BCryptPasswordEncoder();
}
}

请注意,我们使用简单的内存中身份验证,但我们可以简单地将其替换为自定义userDetailsService。

3.4。用户端

最后,我们将创建我们之前在配置中使用的用户端:


@RestController
public class UserController {
@GetMapping("/user/me")
public Principal user(Principal principal) {
 return principal;
}
}

当然,这将使用JSON表示返回用户数据。

4。结论

在本快速教程中,我们专注于使用Spring Security Oauth2Spring Boot实现单点登录。

与往常一样,可以在GitHub上找到完整的源代码。

总结

以上所述是小编给大家介绍的使用Spring Security OAuth2实现单点登录,希望对大家有所帮助

来源:https://www.cnblogs.com/xjknight/p/10965790.html

标签:spring,security,登录
0
投稿

猜你喜欢

  • Spring的@Autowired加到接口上但获取的是实现类的问题

    2023-08-23 21:32:21
  • 浅谈JavaWeb中的web.xml配置部署描述符文件

    2023-11-12 00:14:13
  • Android实现LED发光字效果

    2021-09-14 21:58:12
  • Android自定义TitleView标题开发实例

    2023-09-05 18:21:41
  • jdk-logging log4j logback日志系统实现机制原理介绍

    2022-03-22 11:45:28
  • Java实现图片验证码具体代码

    2021-06-30 13:16:35
  • java 实现MD5加密算法的简单实例

    2023-07-19 21:53:56
  • Kotlin协程启动createCoroutine及创建startCoroutine原理

    2023-01-04 03:05:31
  • Java中关键字synchronized的使用方法详解

    2022-04-14 06:18:54
  • Java上转型和下转型对象

    2021-07-11 13:37:47
  • 浅谈Android View滑动冲突的解决方法

    2021-12-17 06:47:09
  • Java中Thread类详解及常用的方法

    2022-09-29 11:35:44
  • Spark调优多线程并行处理任务实现方式

    2023-08-21 15:43:53
  • Spring Boot整合Swagger测试api构建全纪录

    2022-10-21 09:05:25
  • 浅谈@FeignClient中name和value属性的区别

    2023-11-06 13:04:14
  • WPF实现窗体亚克力效果的示例代码

    2022-07-25 10:38:08
  • DevExpress设置饼状图的Lable位置实例

    2022-02-02 15:53:37
  • Mybatis 缓存原理及失效情况解析

    2022-12-04 07:28:43
  • java实现多人聊天室可视化

    2021-08-27 01:16:49
  • Java模版引擎Freemarker

    2022-10-12 22:20:46
  • asp之家 软件编程 m.aspxhome.com