概述

单点登录(SSO,Single Sign-On)是一种身份验证机制,允许用户通过一次登录获取对多个相关但独立的软件系统或应用的访问权限。在单点登录中,用户只需在一个系统中进行身份验证,然后就能够访问与该身份验证相联的其他系统,而无需重新登录或提供认证凭据。

工作步骤

SSO的主要工作原理包括以下几个步骤:

  1. 身份验证:用户在SSO系统中进行身份验证,通常是通过用户名和密码、多因素身份验证等方式。

  2. 颁发令牌:一旦用户通过身份验证,SSO系统会颁发一个令牌(Token),用于标识用户的身份和权限。

  3. 访问其他系统:用户在访问其他相关系统时,系统会向SSO系统发送令牌进行验证。如果令牌有效且授权通过,用户就可以无需重新登录,直接访问该系统。

  4. 令牌刷新:在一定时间后,令牌可能会过期,需要刷新或重新获取。用户可以通过重新登录SSO系统或其他方式来刷新令牌。

SSO的优势包括:

  1. 用户体验提升:用户只需登录一次,即可访问多个系统,简化了登录流程,提高了用户体验。
  2. 安全性增强:减少了用户管理多个密码的风险,提高了安全性。
  3. 管理便利:减少了系统管理员对用户身份验证和权限管理的工作量,提高了管理效率。

SSO在企业内部、云服务提供商和多租户系统等场景中都有广泛的应用。常见的SSO实现方式包括基于标准协议的实现,如OAuth、OpenID Connect等,以及各种商业SSO解决方案。

OAuth示例

以下是一个简单的Java应用程序示例,演示如何使用Spring Boot和Spring Security OAuth2实现OAuth认证流程。在这个示例中,我们将使用GitHub作为OAuth提供者,并使用Thymeleaf作为模板引擎来渲染用户界面。

依赖管理

确保在项目的pom.xml文件中添加以下依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

应用配置

在application.properties中配置OAuth客户端信息:

spring.security.oauth2.client.registration.github.client-id=YOUR_GITHUB_CLIENT_ID
spring.security.oauth2.client.registration.github.client-secret=YOUR_GITHUB_CLIENT_SECRET
spring.security.oauth2.client.registration.github.scope=user:email
spring.security.oauth2.client.registration.github.redirect-uri=http://localhost:8080/login/oauth2/code/github

spring.security.oauth2.client.provider.github.user-name-attribute=login
spring.security.oauth2.client.provider.github.user-info-uri=https://api.github.com/user

控制器

编写一个简单的控制器来处理登录和用户信息页面:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class AuthController {

    @GetMapping("/")
    public String index() {
        return "index";
    }

    @GetMapping("/user")
    public String user() {
        return "user";
    }
}

视图

创建index.html和user.html模板文件来展示登录页和用户信息页。

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
    <h1>Login with GitHub</h1>
    <a th:href="@{/oauth2/authorization/github}">Login with GitHub</a>
</body>
</html>

user.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>User Info</title>
</head>
<body>
    <h1>User Information</h1>
    <p>Welcome, <span th:text="${#authentication.name}"></span>!</p>
    <p>Email: <span th:text="${#authentication.details.email}"></span></p>
    <a href="/logout">Logout</a>
</body>
</html>

启动应用

运行Spring Boot应用,并访问http://localhost:8080/,点击"Login with GitHub"链接进行OAuth认证。完成认证后,将会跳转到用户信息页面显示认证后的用户信息。

程序还可以根据需要进行进一步扩展和定制,例如添加更多的用户信息,处理认证失败等情况。