Spring Cloud Security实现单点登录

搭建认证服务端和客户端环境,使得在服务端进行验证登录后可以在客户端直接访问

一、搭建客户端环境

  • 添加依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </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>
    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
        <version>0.9.0</version>
    </dependency>
    
  • 添加配置

    server:
      port: 8082
      servlet:
        context-path: /
        session:
          cookie:
            # 设置Cookie,防止Cookie冲突
            name: OAUTH2-CLIENT-SESSIONID
    spring:
      application:
        name: sso-client
    
    # 配oauth2的认证    
    oauth2-server-url: http://localhost:8081
    security:
      oauth2:
        client:
          client-id: admin
          client-secret: admin123456
          user-authorization-uri: ${oauth2-server-url}/oauth/authorize
          access-token-uri: ${oauth2-server-url}/oauth/token
        resource:
          jwt:
            key-uri: ${oauth2-server-url}/oauth/token_key
    
  • 添加启动器类

    @SpringBootApplication
    @EnableOAuth2Sso
    public class SsoClientApplication {
        public static void main(String[] args) {
            SpringApplication.run(SsoClientApplication.class, args);
        }
    }
    
  • 添加配置类

    @Configuration
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    @Order(101)
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        
    }
    
  • 添加控制器类

    @RestController
    @RequestMapping("user")
    public class UserController {
    
        @GetMapping("/info")
        public Object getCurrentUser(Authentication authentication) {
    
            return authentication;
        }
        
        @PreAuthorize("hasAuthority('admin')")
        @GetMapping("/msg")
        public String getMessage(){
            return "您拥有admin权限,可以访问!";
        }
    }
    

二、搭建服务端环境

在原有的整合JWT存储Token的环境代码基础上修改

  • 修改认证服务器配置类

    @Configuration
    @EnableAuthorizationServer
    public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    
        @Autowired
        private PasswordEncoder passwordEncoder;
    
        @Autowired
        private AuthenticationManager authenticationManager;
    
        @Autowired
        private UserDetailServiceImpl userDetailsService;
    
        @Autowired
        @Qualifier("jwtTokenStore")
        private TokenStore tokenStore;
        @Autowired
        private JwtAccessTokenConverter jwtAccessTokenConverter;
    
        /**
         * 使用密码模式所需配置
         */
        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
            endpoints.authenticationManager(authenticationManager)
                    .userDetailsService(userDetailsService)
                    .tokenStore(tokenStore)
                    .accessTokenConverter(jwtAccessTokenConverter);
        }
    
        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            clients.inMemory()
                    // 配置client_id
                    .withClient("admin") 
                    // 配置client_secret
                    .secret(passwordEncoder.encode("admin123456")) 
               		// 配置访问token的有效期
                    .accessTokenValiditySeconds(3600) 
                	// 配置刷新token的有效期
                    .refreshTokenValiditySeconds(864000) 
                	// 配置redirect_uri,用于授权成功后跳转
                    .redirectUris("http://127.0.0.1:8082/login") 
                	// 是否开启登录后自动授权
                	.autoApprove(true) 
                	// 配置scope,申请的权限范围
                    .scopes("all") 
                    // 配置grant_type,授权的模式
                    .authorizedGrantTypes("authorization_code", "password"); 
        }
    
        /**
         * 获取密钥需要身份认证,使用单点登录时必须配置
         */
        @Override
        public void configure(AuthorizationServerSecurityConfigurer security) {
    
            security.tokenKeyAccess("isAuthenticated()");
        }
    }
    

三、测试单点登录

启动 sso-client 和 sso-server 两个微服务

  • 利用网页测试

    • 访问地址:http://localhost:8082/user/info

      在这里插入图片描述

    • 登录授权后跳转到访问的页面

      在这里插入图片描述

  • 利用Postman测试

    • 访问接口

      在这里插入图片描述

    • 点击GetNewToken按钮

      在这里插入图片描述

    • 点击登录

      在这里插入图片描述

    • 点击使用Token并测试接口

      在这里插入图片描述

四、测试权限验证

使用权限为client的用户进行登录

访问地址:http://127.0.0.1:8082/user/msg

在这里插入图片描述

使用权限为admin的用户进行登录

访问地址:http://127.0.0.1:8082/user/msg

在这里插入图片描述


【源码地址】:GitHub

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程小吉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值