• Spring Cloud Security集成CAS (单点登录)对微服务认证


    一、前言

      由于leader要求在搭好的spring cloud 框架中加入对微服务的认证包括单点登录认证,来确保系统的安全,所以研究了Spring Cloud Security这个组件。在前面搭好的demo中,如何确保微服务的安全,为整个系统添加安全控制,就需要用到Spring Cloud Security。用户通过服务网关zuul来访问任何一个微服务的时候,都需要跳转到第三方的认证比如github或者自己搭好的CAS单点登录服务,当认证通过才能访问对应的服务。在研究spring cloud security 之前先对一些概念进行了解了。

      OAuth2(重点),参考文档:http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html
      Spring Security OAuth2,参考文档:http://docs.spring.io/spring-boot/docs/1.5.2.RELEASE/reference/htmlsingle/#boot-features-security-oauth2

      在这个文章中主要记录当用户通过服务网关zuul入口访问任何一个微服务。需要先跳转到GitHub,使用Github进行认证,认证通过之后才能跳转到访问我们提供的微服务。

    二、详细实现

    2.1 准备工作

      (1) 前往https://github.com/settings/developers,点击“Register a new application”按钮,添加一个应用。点击按钮后,界面如下图所示。Homepage URL 和callback url是写zuul的端口。
    图片描述
    (2) 点击“Register application”按钮,即可出现如下图的界面。
    图片描述
    记住这边的Client ID以及Client Secret,后面有用。
    至此,准备工作就完成了。

    2.2 编码

      代码测试成功之后的Github地址:https://github.com/LoveIpo/spring-cloud-demo/tree/master/Zuul_CAS这个Zuul_CAS是在zuul中进一步完善!

    在这里,我们正式进行编码。因为我是在服务网关zuul中添加单点登录的服务认证授权。所以对前面demo中的zuul 工程进一步完善。
    (1) 在pom.xml文件为应用添加spring-cloud-starter-oauth2、spring-cloud-starter-security两个依赖。

    <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-zuul</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-eureka</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-oauth2</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-security</artifactId>
            </dependency>
        </dependencies>

    (2) 在zuul的启动类中添加如下代码

    @SpringBootApplication
    @EnableZuulProxy
    @RestController
    public class GatewayApplication {
    
    
        public static void main(String[] args) {
            SpringApplication.run(GatewayApplication.class, args);
        }
        
        @GetMapping("/")
        public String welcome() {
            return "welcome";
        }
    
        @RequestMapping("/user")
        public Principal user(Principal user) {
            return user;
        }
        
        @Component
        @EnableOAuth2Sso // 实现基于OAuth2的单点登录,建议跟踪进代码阅读以下该注解的注释,很有用
        public static class SecurityConfiguration extends WebSecurityConfigurerAdapter {
            @Override
            public void configure(HttpSecurity http) throws Exception {
                http.
                        antMatcher("/**")
                        // 所有请求都得经过认证和授权
                        .authorizeRequests().anyRequest().authenticated()
                        .and().authorizeRequests().antMatchers("/","/anon").permitAll()
                        .and()
                        // 这里之所以要禁用csrf,是为了方便。
                        // 否则,退出链接必须要发送一个post请求,请求还得带csrf token
                        // 那样我还得写一个界面,发送post请求
                        .csrf().disable()
                        // 退出的URL是/logout
                        .logout().logoutUrl("/logout").permitAll()
                        // 退出成功后,跳转到/路径。
                        .logoutSuccessUrl("/login");
            }
        }
    }
    

      如代码所示,在这里,我们使用@EnableOAuth2Sso 注解,启用了“基于OAuth2的单点登录”,做了一些安全配置;同时,还定义了两个端点,/ 端点返回“welcome”字符串,/user 端点返回当前登录用户的认证信息。

      这里说明一下,@EnableOAuth2Sso注解。如果WebSecurityConfigurerAdapter类上注释了@EnableOAuth2Sso注解,那么将会添加身份验证过滤器和身份验证入口。

      如果只有一个@EnableOAuth2Sso注解没有编写在WebSecurityConfigurerAdapter上,那么它将会为所有路径启用安全,并且会在基于HTTP Basic认证的安全链之前被添加。详见@EnableOAuth2Sso的注释。

    (3) 修改zuul 的application.yml文件,部分代码如下

    server:
      port: 7073
    security:
      user:
        password: user  # 直接登录时的密码
      ignored: /
      sessions: never   # session策略
      oauth2:
        sso:
          loginPath: /login   # 登录路径
        client:
          clientId: 你的clientId
          clientSecret: 你的clientSecret
          accessTokenUri: https://github.com/login/oauth/access_token
          userAuthorizationUri: https://github.com/login/oauth/authorize
        resource:
          userInfoUri: https://api.github.com/user
          preferTokenInfo: false
    spring:
      application:
        name: zuul
    eureka:
      client:
        serviceUrl:
          defaultZone: http://localhost:7071/eureka/
    

      这样,通过服务网关zuul来访问任何一个服务都要跳转到github进行认证的主要代码就编写完成了。

    2.3 测试

    (1) 启动Eureka、zuul、serviceA

    (2) 当通过服务网关zuul(端口7073) 访问serviceA 的url:http://localhost:7073/api-a/add?a=111&b=113时。页面会自动跳转到github进行认证。你也可以通过zuul访问serviceB也会自动跳转到github进行认证之后才能回调到serviceB。

    (3) 当输入github的用户名和密码认证通过之后,会出现serviceA的调用结果。如下图所示


    图片描述
    图片描述
    (4) 当你认证通过之后输入http://localhost:7073/user 可以看到你github 的用户信息。

  • 相关阅读:
    KVM安装以及远程连接
    开博客祭
    CQOI 2021
    琐记——学长们
    大事祭
    关于洛谷与博客园的博客的一些声明
    CSP-S 2020 & NOIP 2020 日记与游记
    调和级数
    快速乘
    二叉堆
  • 原文地址:https://www.cnblogs.com/liboware/p/12528573.html
Copyright © 2020-2023  润新知