Skip to content

OAuth2 单点登录

本文档介绍后端工程使用 OAuth2 协议作为资源服务器接入 sso 单点认证服务,配置文件做个性化的设置

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

maven pom.xml 修改

添加oauth依赖包

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

如果需要使用 snapshot 版本,还需添加私服仓库方能下载

xml
    <repositories>
        <repository>
            <id>nexus</id>
            <name>local private nexus</name>
            <url>https://svn.youshengyun.com:9900/nexus/repository/maven-public/</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>nexus</id>
            <name>local private nexus</name>
            <url>https://svn.youshengyun.com:9900/nexus/repository/maven-public/</url>
        </pluginRepository>
    </pluginRepositories>

修改属性文件application.yml

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

yaml
y9:
    feature:
        oauth2:
            resource:
                enabled: true
                saveLogMessage: false
                saveOnlineMessage: false
                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

登录用户信息获取

前端登录成功后可拿到 accessToken,调用接口时会一并发送到后台,后台拿到 accessToken 会再次去单点登录服务器校验,校验成功后会把相应的登录用户信息设置到 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.