Skip to content

OAuth2/OIDC 单点登录

简介

本文档介绍 SpringBoot 后端工程使用 OAuth2/OIDC 协议作为资源服务器接入数字底座 SSO 单点认证服务,提供了对访问受保护资源的令牌验证机制,不涉及 SSO 认证中心的部署与登录流程。

Y9Oauth2ResourceFilter 是核心组件,实现了 Java Servlet 过滤器接口,主要处理流程如下:

  1. 从 HTTP 请求头 Authorization: Bearer <token> 或查询参数 access_token=<token> 中提取访问令牌 access_token
  2. 调用 SSO 服务器的 introspection 端点对令牌进行验证
  3. 解析令牌中的用户信息并存储到会话中
  4. 设置当前用户上下文 net.risesoft.y9.Y9LoginUserHolder 中供后续业务逻辑使用

关于前后端分离的系统做单点登录对接的完整流程可以查看OAuth2 接口文档 ,下面的文档中的内容是针对于应用系统后端的对接说明

功能引用

添加依赖

xml

<dependency>
    <groupId>net.risesoft</groupId>
    <artifactId>risenet-y9boot-starter-sso-oauth2-resource</artifactId>
    <version>[最新正式版本]</version>
</dependency>

如需使用 SNAPSHOT 版本,且 maven 没有 POM 继承链至数字底座的 y9-digitalbase-parent 则还需将有生的私服仓库地址添加到 pom.xml 文件中。

xml
<repositories>
    <repository>
        <id>y9-internet-repo</id>
        <url>https://svn.youshengyun.com:9900/nexus/repository/maven-public/</url>
        <releases>
            <enabled>true</enabled>
        </releases>
        <snapshots>
            <enabled>true</enabled>
            <!-- <updatePolicy>always</updatePolicy> -->
            <!-- always,daily(default),interval:XXX,never -->
        </snapshots>
    </repository>
</repositories>

修改配置文件

protectedUrlPatterns 这个配置项设置需要拦截的URL,可以配置多个拦截以,分割

yaml
y9:
    feature:
        oauth2:
            resource:
                enabled: true
                allowBasicAuthentication: true
                allowFormEncodedBodyParameter: true
                allowUriQueryParameter: true
                protectedUrlPatterns: /api,/vue
                opaque:
                    client-id: clientid
                    client-secret: secret
                    introspection-uri: http://localhost:7055/sso/oauth2.0/introspect
                    profile-uri: http://localhost:7055/sso/oauth2.0/profile

示例代码

通过当前用户上下文 net.risesoft.y9.Y9LoginUserHolder 这个类获取到当前租户id,当前登录用户信息等。

java
        // 当前登录用户信息
UserInfo userInfo = Y9LoginUserHolder.getUserInfo();
// 当前租户id
String tenantId = Y9LoginUserHolder.getTenantId();

示例项目

示例项目地址:https://gitee.com/risesoft-y9/y9-core/y9-digitalbase-example/risenet-y9demo-sso-oauth2

其中 backend-demo 为后端工程示例,frontend-vue3-demo 为前端工程示例。

Released under the GPL-3.0 License.