Spring Cloud Gateway + OAuth2 + JWT 单点登录(SSO)实现方案

发布于:2025-06-18 ⋅ 阅读:(20) ⋅ 点赞:(0)
一、概述

基于Spring Cloud微服务架构,通过Gateway网关、OAuth2协议和JWT令牌实现分布式系统的单点登录,允许用户一次登录后访问所有互信的微服务。核心技术组件包括:

  • Spring Cloud Gateway:统一请求入口,负责路由、Token验证和转发
  • OAuth2协议:定义授权流程,实现用户认证和授权码交换
  • JWT(Json Web Token):作为无状态令牌载体,包含用户身份和权限信息
二、系统架构与服务组件
1. 服务架构图
+----------------+     +----------------+     +----------------+
|                |     |                |     |                |
|  客户端应用     |<--->|   API网关      |<--->|  认证中心      |
|  (sso-client)   |     |  (api-gateway) |     | (sso-auth-server)|
|                |     |                |     |                |
+----------------+     +--------+-------+     +--------+-------+
                                           |
                                           v
+----------------+     +----------------+
|                |     |                |
|  用户服务       |     |  订单服务      |
| (user-service)  |     |(order-service)|
|                |     |                |
+----------------+     +----------------+
2. 服务职责说明
服务名称 职责描述
认证中心 处理用户登录、生成JWT令牌、管理客户端注册信息,作为OAuth2授权服务器
API网关 统一请求入口,实现路由分发、Token验证与传递,集成OAuth2客户端配置
资源服务 提供业务数据接口(如用户、订单服务),验证Token并基于权限控制访问
客户端应用 用户交互入口,引导登录、获取Token并调用资源服务,展示业务数据
三、核心技术实现
1. 认证中心(auth-server)配置
<!-- 认证中心依赖配置(pom.xml) -->
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-oauth2</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-oauth2-jose</artifactId>
    </dependency>
</dependencies>
// 认证服务器核心配置(AuthorizationServerConfig.java)
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
   
    @Autowired private AuthenticationManager authenticationManager;
    @Autowired private UserDetailsService userDetailsService;
    @Autowired private TokenStore tokenStore;
    @Autowired private JwtAccessTokenConverter accessTokenConverter;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
   
        clients.inMemory()
            .withClient("sso-client")
            .secret("{noop}sso-secret")
            .authorizedGrantTypes("authorization_code", "refresh_token", "password")
            .scopes("read", "write", "profile")
            .redirectUris("http://localhost:8081/login/oauth2/code/custom")
            .accessTokenValiditySeconds(3600)
            .refreshTokenValiditySeconds(86400);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
   
        endpoints.authenticationManager(authenticationManager)
                 .userDetailsService(userDetailsService)
                 .tokenStore(tokenStore)
                 .accessTokenConverter(accessTokenConverter)
                 .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
    }
}
// Spring Security配置(SecurityConfig.java)
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
   
    @Bean
    @Override
    public UserDetailsService userDetailsServiceBean() throws Exception {
   
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(
            User.withUsername("user")
                .password("{noop}password")
                .roles("USER")
                .authorities("READ", "WRITE")
                .build()
        );
        return manager;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
   
        http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/oauth/authorize", "/login").permitAll()
   

网站公告

今日签到

点亮在社区的每一天
去签到