(流程图 + 代码)带你实现单点登陆SSO(三)

简介: (流程图 + 代码)带你实现单点登陆SSO

5. 两个客户端

5.1. Maven依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/><!-- lookup parent from repository -->
    </parent>
    <groupId>com.cjs.sso</groupId>
    <artifactId>oauth2-sso-client-member</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>oauth2-sso-client-member</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</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-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security.oauth.boot</groupId>
            <artifactId>spring-security-oauth2-autoconfigure</artifactId>
            <version>2.1.3.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-springsecurity5</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

5.2. application.yml

server:
  port: 8082
  servlet:
    context-path: /memberSystem
security:
  oauth2:
    client:
      client-id: UserManagement
      client-secret: user123
      access-token-uri: http://localhost:8080/oauth/token
      user-authorization-uri: http://localhost:8080/oauth/authorize
    resource:
      jwt:
        key-uri: http://localhost:8080/oauth/token_key

00a98d154e43cfaa7b670cd03a0af395_640_wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1.png

这里context-path不要设成/,不然重定向获取code的时候会被拦截

5.3. WebSecurityConfig

package com.cjs.example.config;
import com.cjs.example.util.EnvironmentUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
 * @author ChengJianSheng
 * @date 2019-03-03
 */
@EnableOAuth2Sso
@Configuration
publicclass WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private EnvironmentUtils environmentUtils;
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/bootstrap/**");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        if ("local".equals(environmentUtils.getActiveProfile())) {
            http.authorizeRequests().anyRequest().permitAll();
        }else {
            http.logout().logoutSuccessUrl("http://localhost:8080/logout")
                    .and()
                    .authorizeRequests()
                    .anyRequest().authenticated()
                    .and()
                    .csrf().disable();
        }
    }
}

说明:

  1. 最重要的注解是@EnableOAuth2Sso
  2. 权限控制这里采用Spring Security方法级别的访问控制,结合Thymeleaf可以很容易做权限控制
  3. 顺便多提一句,如果是前后端分离的话,前端需求加载用户的权限,然后判断应该显示那些按钮那些菜单

5.4. MemberController

package com.cjs.example.controller;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.security.Principal;
/**
 * @author ChengJianSheng
 * @date 2019-03-03
 */
@Controller
@RequestMapping("/member")
publicclass MemberController {
    @GetMapping("/list")
    public String list() {
        return"member/list";
    }
    @GetMapping("/info")
    @ResponseBody
    public Principal info(Principal principal) {
        return principal;
    }
    @GetMapping("/me")
    @ResponseBody
    public Authentication me(Authentication authentication) {
        return authentication;
    }
    @PreAuthorize("hasAuthority('member:save')")
    @ResponseBody
    @PostMapping("/add")
    public String add() {
        return"add";
    }
    @PreAuthorize("hasAuthority('member:detail')")
    @ResponseBody
    @GetMapping("/detail")
    public String detail() {
        return"detail";
    }
}

5.5. Order项目跟它是一样的

server:
  port: 8083
  servlet:
    context-path: /orderSystem
security:
  oauth2:
    client:
      client-id: OrderManagement
      client-secret: order123
      access-token-uri: http://localhost:8080/oauth/token
      user-authorization-uri: http://localhost:8080/oauth/authorize
    resource:
      jwt:
        key-uri: http://localhost:8080/oauth/token_key

5.6. 关于退出

退出就是清空用于与SSO客户端建立的所有的会话,简单的来说就是使所有端点的Session失效,如果想做得更好的话可以令Token失效,但是由于我们用的JWT,故而撤销Token就不是那么容易,关于这一点,在官网上也有提到:

45dca7e151397691c3e809b7a24b52cf_640_wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1.png

本例中采用的方式是在退出的时候先退出业务服务器,成功以后再回调认证服务器,但是这样有一个问题,就是需要主动依次调用各个业务服务器的logout

6. 工程结构

6389d75964931b0a65cb1c2ad44ceece_640_wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1.png

附上源码:https://github.com/chengjiansheng/cjs-oauth2-sso-demo.git

7. 演示

255f7c337fcf123c35163e99e41ca45b_640_wx_fmt=jpeg&wxfrom=5&wx_lazy=1&wx_co=1.jpg

8. 参考

https://www.cnblogs.com/cjsblog/p/9174797.html

https://www.cnblogs.com/cjsblog/p/9184173.html

https://www.cnblogs.com/cjsblog/p/9230990.html

https://www.cnblogs.com/cjsblog/p/9277677.html

https://blog.csdn.net/fooelliot/article/details/83617941

http://blog.leapoahead.com/2015/09/07/user-authentication-with-jwt/

https://www.cnblogs.com/lihaoyang/p/8581077.html

https://www.cnblogs.com/charlypage/p/9383420.html

http://www.360doc.com/content/18/0306/17/16915_734789216.shtml

https://blog.csdn.net/chenjianandiyi/article/details/78604376

https://www.baeldung.com/spring-security-oauth-jwt

https://www.baeldung.com/spring-security-oauth-revoke-tokens

https://www.reinforce.cn/t/630.html

9. 文档

https://projects.spring.io/spring-security-oauth/docs/oauth2.html

https://docs.spring.io/spring-security-oauth2-boot/docs/2.1.3.RELEASE/reference/htmlsingle/

https://docs.spring.io/spring-security-oauth2-boot/docs/2.1.3.RELEASE/

https://docs.spring.io/spring-security-oauth2-boot/docs/

https://docs.spring.io/spring-boot/docs/2.1.3.RELEASE/

https://docs.spring.io/spring-boot/docs/

https://docs.spring.io/spring-framework/docs/

https://docs.spring.io/spring-framework/docs/5.1.4.RELEASE/

https://spring.io/guides/tutorials/spring-boot-oauth2/

https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#core-services-password-encoding

https://spring.io/projects/spring-cloud-security

https://cloud.spring.io/spring-cloud-security/single/spring-cloud-security.html

https://docs.spring.io/spring-session/docs/current/reference/html5/guides/java-security.html

https://docs.spring.io/spring-session/docs/current/reference/html5/guides/boot-redis.html#boot-spring-configuration


相关文章
|
JavaScript 前端开发 Android开发
转换 ES6 代码时需要注意哪些兼容性问题
在转换ES6代码时,需关注兼容性问题,如箭头函数、模板字符串、let/const等语法在旧浏览器中的支持情况,以及模块化、类、Promise等特性是否需要polyfill。使用Babel等工具可有效解决大部分兼容性问题。
|
数据安全/隐私保护 网络架构
DSL线路如何工作?
【4月更文挑战第15天】
802 3
DSL线路如何工作?
|
网络协议 数据安全/隐私保护 网络架构
软路由R4S+iStoreOS实现公网远程桌面局域网内电脑
软路由R4S+iStoreOS实现公网远程桌面局域网内电脑
1083 0
|
分布式计算 JavaScript 前端开发
JS中数组22种常用API总结,slice、splice、map、reduce、shift、filter、indexOf......
JS中数组22种常用API总结,slice、splice、map、reduce、shift、filter、indexOf......
533 0
|
1月前
|
人工智能 API 开发工具
2026年 AI 大模型 LLM API 应用开发指南:从原理到工程实践
本文将带你从零开始深入了解LLM(大语言模型)API开发。我们将剥离复杂的数学原理,专注于工程实践,涵盖从核心概念(Token、Prompt、Temperature)到环境配置、API选择、以及构建真实对话应用的完整流程。如果你是正在寻求AI转型的开发者,或者希望快速将LLM能力集成到产品中的工程师,这篇文章将是你的最佳起点。
650 3
react-Native init初始化项目报错”TypeError: cli.init is not a function“
react-Native init初始化项目报错”TypeError: cli.init is not a function“
1338 1
|
9月前
|
人工智能 自然语言处理 算法
大模型时代的企业“人才”效率革命:从个体到组织的蜕变之路
在AI技术飞速发展的今天,生成式人工智能正深刻改变职场生态。本文从认知重构、能力跃迁、价值共生三个维度探讨人机协同的未来:通过系统学习实现从工具依赖到人机协作的转变;构建“技术-应用-伦理”三维竞争力模型;以个人成长与企业赋能双向促进,实现人才价值升级。GAI认证成为关键桥梁,助力职场人在变革中把握机遇,与技术共舞,迈向更高层次创造。
|
存储 缓存 JavaScript
一文带你了解vuex和使用(2024年11月)
欢迎来到我的博客,我是自学前端两年半的大一学生,熟悉JavaScript与Vue,正向全栈发展。本篇介绍了Vuex,Vue.js的状态管理模式,包括其核心概念如state、getter、mutation、action及模块化使用,通过集中管理状态确保应用状态的可预测变化。文章详细解析了Vuex的工作原理,特别是与Vue的computed属性和响应式系统的集成,以及如何在实际项目中搭建和使用Vuex。如果你觉得有帮助,欢迎关注,我将持续更新更多技术文章。🎉🎉🎉
1326 0
|
JavaScript
Node.js单点登录SSO详解:Session、JWT、CORS让登录更简单(二)
Node.js单点登录SSO详解:Session、JWT、CORS让登录更简单(一)
612 0
|
存储 JavaScript 前端开发
在vue项目中实现单点登录
在vue项目中实现单点登录
1139 1

热门文章

最新文章