【Spring Boot】Spring Boot @EnableOAuth2Sso | 启用 OAuth2 单点登录

本页将介绍Spring Security OAuth2 @EnableOAuth2Sso注解的例子。

@EnableOAuth2Sso注解可以启用OAuth2单点登录(SingleSignOn,SSO)。默认情况下,所有的路径都是需要安全的。

我们可以在Spring SecurityJava配置中使用WebSecurityConfigurerAdapter来定制它。我们可以使用application.propertiesapplication.yml或以命令行方式配置Spring Security OAuth2

这里我们将使用GitHub创建Spring Boot OAuth2应用程序。

演示工具版本

  1. Java 11
  2. Spring 5.1.7.RELEASE
  3. Spring Boot 2.1.5.RELEASE
  4. Maven 3.5.2

Maven 依赖

找到OAuth2Maven依赖。

<dependency>
	<groupId>org.springframework.security.oauth.boot</groupId>
	<artifactId>spring-security-oauth2-autoconfigure</artifactId>
	<version>2.1.5.RELEASE</version>
</dependency> 

Spring Boot应用程序中,上述依赖关系在类路径上的可用性为我们提供了自动配置OAuth2的优势。

使用 @EnableOAuth2Sso

要在我们的应用程序中使用@EnableOAuth2Sso,请在Spring Security配置中用@Configuration对其进行注释。

@Configuration
@EnableOAuth2Sso
public class SecurityConfiguration {
} 

现在所有的URL都是需要安全验证的。我们可以使用WebSecurityConfigurerAdapter来自定义这一行为。假设我们想使用一些不进行安全验证的URL,如主页和错误页面等,如下进行配置。

SecurityConfiguration.java

package com.concretepage;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableOAuth2Sso
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
	   @Override
	    protected void configure(HttpSecurity http) throws Exception {
	        http
	            .authorizeRequests()
	            .antMatchers("/", "/error**").permitAll()
                    .anyRequest().authenticated()
                    .and().logout().logoutUrl("/logout")
		    .logoutSuccessUrl("/");

	    }
} 

OAuth2 配置

Spring Boot应用程序中,我们可以使用application.propertiesapplication.yml或以命令行方式配置安全OAuth2客户端、资源和sso属性。

在我们的例子中,我们使用的是GitHub OAuth

application.yml

security:
  oauth2:
   client:
     clientId: <your_github_clientId>
     clientSecret: <your_github_clientSecret>
     accessTokenUri: https://github.com/login/oauth/access_token
     userAuthorizationUri: https://github.com/login/oauth/authorize
     clientAuthenticationScheme: form
   resource:
     userInfoUri: https://api.github.com/user
   sso:
     login-path: /login 

你需要在上述YML文件中输入你的GitHubclientIdclientSecret

clientId: 这是OAuth客户端的IDOAuth提供商通过它来识别客户端。

clientSecret: 与资源关联的客户端密钥。

要获得GitHubOAuth2客户端ID和客户端密钥,请通过该链接

登出

要注销Spring Security应用程序,请在Spring Security Java配置文件中配置注销URL,默认为/logout,然后创建一个表单并以POST方式提交给注销URL。用Thymeleaf查找示例表单。

<form th:action="@{/logout}" method="POST">
      <input type="submit" value="Logout"/>
</form> 

完整示例

这里我们将提供我们的演示程序的完整代码。文章中已经给出了SecurityConfiguration.javaapplication.yml这两个文件。查找其余的代码。

pom.xml

<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.1.5.RELEASE</version>
	<relativePath />
</parent>
<properties>
	<context.path>spring-app</context.path>
	<java.version>11</java.version>
</properties>
<dependencies>
	<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.boot</groupId>
		<artifactId>spring-boot-starter-thymeleaf</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.security.oauth.boot</groupId>
		<artifactId>spring-security-oauth2-autoconfigure</artifactId>
		<version>2.1.5.RELEASE</version>
	</dependency>
</dependencies> 

AppController.java

package com.concretepage;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class AppController {
	@GetMapping("hello")
	public ModelAndView welcome() {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("welcome");
		return mav;
	}

	@GetMapping("error")
	public ModelAndView error() {
		ModelAndView mav = new ModelAndView();
		return mav;
	}
} 

index.html

<!doctype html>
<html>
<head>
  <title>Spring Security</title>
</head>
<body>
   <h3>Login with <a href="/hello">GitHub</a></h3>
</body>
</html> 

welcome.html

<!doctype html>
<html lang="en">
<head>
    <title>Welcome</title>
</head>
<body>
   Welcome <b th:inline="text" > [[${#httpServletRequest.remoteUser}]] </b> <br/><br/>
   <form th:action="@{/logout}" method="POST">
        <input type="submit" value="Logout"/>
   </form>	
</body>
</html> 

error.html

<!doctype html>
<html>
<head>
  <title>Spring Security</title>
</head>
<body>
   <h3>Error</h3>
   <p thif="${param.error}">
       An error occurred.
   </p>
</body>
</html> 

Main.java

package com.concretepage;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Main {
	public static void main(String[] args) {
		SpringApplication.run(Main.class, args);
	}
} 

输出

下载该项目,并在application.yml文件中输入你的GitHub clientIdclientSecret

然后使用命令提示符从项目的根文件夹中运行以下命令。

mvn spring-boot:run 

访问网址

http://localhost:8080/ 

在这里插入图片描述

点击GitHub链接进行登录。你将被重定向到GitHub登录页面。登录成功后,你将被重定向到你的应用程序并看到欢迎页面。

在这里插入图片描述

参考文献

【1】OAuth2 Boot
【2】OAuth 2 Developers Guide

源码下载

提取码:mao4

spring-boot-enableoauth2sso.zip

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猫巳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值