基于oauth2简单实现SSO

本文详细介绍如何使用Spring Cloud和OAuth2搭建单点登录(SSO)系统,包括认证服务器和客户端的配置过程,以及JWT令牌的使用。通过具体代码示例,展示如何避免重复登录,实现跨应用的安全身份验证。
  • 在实现SSO之前,先要说一下**@EnableResourceServer@EnableOAuth2Sso**
  1. 一般网关处我们使用EnableResourceServer时,可以支持任意的oauth2授权模型,网关声明称资源服务器可以配置ResourceServerConfigurerAdapter,我们可以配置放行的路径等等内容。
  2. 如果网关处使用EnableOAuth2Sso,在所有请求转发之前就首先要到认证服务器上去校验信息,使用授权码模式,clientid与clientsecret来确认进行oauth2的登陆,跳转登陆页面在进行登陆。

下面我们来简单搭建一个SSO的小项目
  • 搭建认证服务器

    我们将客户端信息存储在mysql中,token使用jwt。

    依赖包只需要oauth2,我cloud用的版本是Greenwich.SR2

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-oauth2</artifactId>
    </dependency>
    
    1. 配置AuthorizationServerConfigurerAdapter

      package cn.hs.sys.config;
      
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;
      import org.springframework.security.authentication.AuthenticationManager;
      import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
      import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
      import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
      import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
      import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
      import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
      import org.springframework.security.oauth2.provider.token.TokenStore;
      import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
      import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
      
      import javax.sql.DataSource;
      
      /**
       * @description:
       * @Author: huangsan
       * @Date: 2020/5/8 4:46 下午
       */
      @Configuration
      @EnableAuthorizationServer
      public class OAuth2AuthServerConfig extends AuthorizationServerConfigurerAdapter {
             
             
      
          @Autowired
          private AuthenticationManager au
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值