栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringCloudAlibaba篇(九)SpringCloudGateWay整合Oauth2+Jwt实现认证中心

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringCloudAlibaba篇(九)SpringCloudGateWay整合Oauth2+Jwt实现认证中心

SpringCloudAlibaba篇(八)SpringCloudGateWay聚合swagger3、SpringBoot2.6.X整合swagger3+knife4j

文章目录
  • 前言
  • 采用技术栈
  • 父工程依赖及统一版本
  • 1. 搭建Oauth2-server
    • 1.1 oauth2-server 依赖
    • 1.2 bootstrap.yml
      • mysql-oauth2.yaml
      • log.properties
      • zipkin.yaml
      • mybatis-plus.yaml
      • redis.yaml
    • 1.3 keytool生成RSA证书
    • 1.4 SysUserServiceImpl 用户信息实现类
    • 1.6 Oauth2ServerConfig 认证服务器配置
    • 1.7 获取RSA公钥接口
    • 1.8 配置Spring Security,允许获取公钥接口的访问
    • 1.9 初始化用户权限demo
    • 1.10 Redis相关配置
  • 2. gateway
    • 2.1 网关依赖
    • 2.2 applicaion.yaml
    • 2.3 bootstrap.yaml
      • gateway.yaml
      • sentinel.yaml
      • log.properties
      • redis.yaml
    • 2.4 鉴权管理器
    • 2.5 自定义返回结果:没有登录或token过期时
    • 2.6 自定义返回结果:没有权限访问时
    • 2.7 网关白名单配置
    • 2.8 Redis相关配置
    • 2.9 资源服务器配置
    • 2.10 将登录用户的JWT转化成用户信息的全局过滤器
    • 2.11 白名单路径访问时需要移除JWT请求头
  • 测试

前言

通常微服务的认证和授权思路有两种:

  • 网关只负责转发请求,认证鉴权交给每个微服务控制
  • 统一在网关层面认证鉴权,微服务只负责业务

第二种方案的流程图

采用技术栈


父工程依赖及统一版本

附:父工程依赖

    pom

    
        1.0.0
        UTF-8
        UTF-8
        1.8
        3.8.1
        2.6.3
        2021.0.1
        2021.0.1.0
        1.4.2
        1.8.3
        2.7.15
        4.9.2
        1.4.2
        3.5.1
        3.0.2
        3.0.0
    

    
        
            
            
                org.springframework.boot
                spring-boot-dependencies
                ${spring.boot.version}
                pom
                import
            
            
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
        
    
    
        
            org.projectlombok
            lombok
            provided
        
        
            io.springfox
            springfox-boot-starter
            3.0.0
        
    
1. 搭建Oauth2-server

1.1 oauth2-server 依赖

引用版本可查看上面的父工程依赖


        
            top.fate
            fate-common
            1.0.0
        
        
            org.springframework.boot
            spring-boot-starter-web
            
            
                
                    spring-boot-starter-logging
                    org.springframework.boot
                
            
        
        
            org.springframework.boot
            spring-boot-starter-actuator
        
        
        
            org.springframework.boot
            spring-boot-starter-log4j2
        
        
        
            org.springframework.cloud
            spring-cloud-starter-bootstrap
        

        
        
            com.alibaba.cloud
            spring-cloud-starter-alibaba-nacos-discovery
            
                
                    com.alibaba.nacos
                    nacos-client
                
            
            ${spring-cloud-alibaba.version}
        
        
            com.alibaba.cloud
            spring-cloud-starter-alibaba-nacos-config
            
                
                    com.alibaba.nacos
                    nacos-client
                
            
            ${spring-cloud-alibaba.version}
        
        
            com.alibaba.nacos
            nacos-client
            ${alibaba.nacos.version}
        

        
        
            com.alibaba
            druid-spring-boot-starter
            1.1.22
        
        
        
            mysql
            mysql-connector-java
            8.0.16
        
        
        
            com.baomidou
            mybatis-plus-boot-starter
            ${mybatis.plus.version}
        
        
        
            org.springframework.cloud
            spring-cloud-starter-zipkin
            2.2.8.RELEASE
        
        
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
        
            com.nimbusds
            nimbus-jose-jwt
            9.9.3
        
        
        
            org.springframework.boot
            spring-boot-starter-security
        
        
            org.springframework.cloud
            spring-cloud-starter-oauth2
            2.2.5.RELEASE
        
        
            cn.hutool
            hutool-all
            5.8.0
        
    
1.2 bootstrap.yml
server:
  port: 9999
url:
  nacos: localhost:8848
spring:
  application:
    name: oauth2-server #实例名
  profiles:
    active: dev
  cloud:
    nacos:
      discovery:
        #集群环境隔离
        cluster-name: shanghai
        #命名空间
        namespace: ${spring.profiles.active}
        #持久化实例 ture为临时实例 false为持久化实例  临时实例发生异常直接剔除, 而持久化实例等待恢复
        ephemeral: true
        #注册中心地址
        server-addr: ${url.nacos}
      config:
        namespace: ${spring.profiles.active}
        file-extension: yaml
        #配置中心地址
        server-addr: ${url.nacos}
        extension-configs[0]:
          data-id: mysql-oauth2.yaml
          group: DEFAULT_GROUP
          refresh: false
        extension-configs[1]:
          data-id: log.properties
          group: DEFAULT_GROUP
          refresh: false
        extension-configs[2]:
          data-id: zipkin.yaml
          group: DEFAULT_GROUP
          refresh: false
        extension-configs[3]:
          data-id: mybatis-plus.yaml
          group: DEFAULT_GROUP
          refresh: false
        extension-configs[4]:
          data-id: redis.yaml
          group: DEFAULT_GROUP
          refresh: false
mysql-oauth2.yaml
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/oauth?useSSL=false&allowPublicKeyRetrieval=true
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
log.properties
logging.level.root=info
zipkin.yaml
spring:
  zipkin:
    base-url: http://127.0.0.1:9411
    sender:
      type: web
    sleuth:
      sampler:
        probability: 1.0
mybatis-plus.yaml
mybatis-plus:
  mapper-locations: classpath:mapper
@Service
public class SysUserServiceImpl implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return SecurityUser.builder()
                .userId(UUID.randomUUID().toString().replaceAll("-",""))
                .username("admin")
                .password(new BCryptPasswordEncoder().encode("123456"))
                .authorities(AuthorityUtils.createAuthorityList("user", "admin"))
                .build();
    }
}

SecurityUser 用户封装类

package top.fate.domain;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;


@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class SecurityUser implements UserDetails {

    private String userId;

    //用户名
    private String username;

    //密码
    private String password;

    //权限+角色集合
    private Collection authorities;

    @Override
    public Collection getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    // 账户是否未过期
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    // 账户是否未被锁
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
## 1.5 JWT内容增强器
```java
package top.fate.component;

import org.s

pringframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;
import top.fate.domain.SecurityUser;

import java.util.HashMap;
import java.util.Map;


@Component
public class JwtTokenEnhancer implements TokenEnhancer {
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
        Map info = new HashMap<>();
        //把用户ID设置到JWT中
        info.put("id", securityUser.getUserId());
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(info);
        return accessToken;
    }
}

1.6 Oauth2ServerConfig 认证服务器配置

加载用户信息的服务UserServiceImpl及RSA的钥匙对KeyPair

package top.fate.config;

import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
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.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;
import top.fate.component.JwtTokenEnhancer;
import top.fate.service.impl.SysUserServiceImpl;

import java.security.KeyPair;
import java.util.ArrayList;
import java.util.List;


@AllArgsConstructor
@Configuration
@EnableAuthorizationServer
public class Oauth2ServerConfig extends AuthorizationServerConfigurerAdapter {

    private final PasswordEncoder passwordEncoder;
    private final SysUserServiceImpl userDetailsService;
    private final AuthenticationManager authenticationManager;
    private final JwtTokenEnhancer jwtTokenEnhancer;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("client-app")
                .secret(passwordEncoder.encode("123456"))
                .scopes("all")
                .authorizedGrantTypes("password", "refresh_token")
                .accessTokenValiditySeconds(3600)
                .refreshTokenValiditySeconds(86400);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        List delegates = new ArrayList<>();
        delegates.add(jwtTokenEnhancer);
        delegates.add(accessTokenConverter());
        enhancerChain.setTokenEnhancers(delegates); //配置JWT的内容增强器
        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService) //配置加载用户信息的服务
                .accessTokenConverter(accessTokenConverter())
                .tokenEnhancer(enhancerChain);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients();
    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        jwtAccessTokenConverter.setKeyPair(keyPair());
        return jwtAccessTokenConverter;
    }

    @Bean
    public KeyPair keyPair() {
        //从classpath下的证书中获取秘钥对
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("jwt.jks"), "123456".toCharArray());
        return keyStoreKeyFactory.getKeyPair("jwt", "123456".toCharArray());
    }

}
1.7 获取RSA公钥接口
package top.fate.controller;

import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.KeyPair;
import java.security.interfaces.RSAPublicKey;
import java.util.Map;


@RestController
@RequestMapping(value = "rsa")
public class KeyPairController {

    @Autowired
    private KeyPair keyPair;

    @GetMapping(value = "publicKey")
    public Map getKey(){
        RSAPublicKey aPublic = (RSAPublicKey) keyPair.getPublic();
        RSAKey key = new RSAKey.Builder(aPublic).build();
        return new JWKSet(key).toJSONObject();
    }
}
1.8 配置Spring Security,允许获取公钥接口的访问
package top.fate.config;

import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .requestMatchers(EndpointRequest.toAnyEndpoint()).permitAll()
                .antMatchers("/rsa/publicKey").permitAll()
                .anyRequest().authenticated();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
1.9 初始化用户权限demo
package top.fate.service.impl;

import cn.hutool.core.collection.CollUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import top.fate.model.SysConstant;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;


@Service
public class ResourceServiceImpl {

    private Map> resourceRolesMap;
    @Resource
    private RedisTemplate redisTemplate;

    @PostConstruct
    public void initData() {
        resourceRolesMap = new TreeMap<>();
        resourceRolesMap.put("/user/tb-user/list", CollUtil.toList("ADMIN"));
        resourceRolesMap.put("/order/order/getUserService", CollUtil.toList("ADMIN", "ROOT"));
        redisTemplate.opsForHash().putAll("oauth2:oauth_urls", resourceRolesMap);
    }
}
1.10 Redis相关配置
package top.fate.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;


@Configuration
@EnableRedisRepositories
public class RedisRepositoryConfig {

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

}
2. gateway 2.1 网关依赖

        
        
            org.springframework.cloud
            spring-cloud-starter-gateway
        
        
            org.springframework.cloud
            spring-cloud-starter-loadbalancer
        
        
        
            com.alibaba.cloud
            spring-cloud-starter-alibaba-sentinel
            ${spring-cloud-alibaba.version}
        
        
        
            com.alibaba.cloud
            spring-cloud-starter-alibaba-nacos-discovery
            
                
                    com.alibaba.nacos
                    nacos-client
                
            
            ${spring-cloud-alibaba.version}
        
        
            com.alibaba.cloud
            spring-cloud-starter-alibaba-nacos-config
            
                
                    com.alibaba.nacos
                    nacos-client
                
            
            ${spring-cloud-alibaba.version}
        
        
            com.alibaba.nacos
            nacos-client
            ${alibaba.nacos.version}
        
        
        
            org.springframework.cloud
            spring-cloud-starter-bootstrap
        
        
        
            org.springframework.boot
            spring-boot-starter-logging
            
                
                    *
                    *
                
            
        
        
            org.springframework.boot
            spring-boot-starter-log4j2
        
        
        
            org.springframework.cloud
            spring-cloud-starter-zipkin
            2.2.8.RELEASE
        
        
            io.zipkin.brave
            brave-instrumentation-dubbo
        

        
            com.github.xiaoymin
            knife4j-spring-boot-starter
            3.0.3
        
        
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
        
        
            org.springframework.security
            spring-security-config
        
        
            org.springframework.security
            spring-security-oauth2-resource-server
        
        
            org.springframework.security
            spring-security-oauth2-client
        
        
            org.springframework.security
            spring-security-oauth2-jose
        
        
            com.nimbusds
            nimbus-jose-jwt
            9.9.3
        
        
            cn.hutool
            hutool-all
            5.8.0
        
        
            top.fate
            fate-common
            1.0.0
        
    
2.2 applicaion.yaml
  spring:
    security:
      oauth2:
        resourceserver:
          jwt:
            jwk-set-uri: 'http://localhost:9999/rsa/publicKey'
secure:
  ignore:
    urls: #配置白名单路径
      - "/actuator
@Component
public class AuthorizationManager implements ReactiveAuthorizationManager {
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public Mono check(Mono mono, AuthorizationContext authorizationContext) {
        //从Redis中获取当前路径可访问角色列表
        URI uri = authorizationContext.getExchange().getRequest().getURI();
        Object obj = redisTemplate.opsForHash().get("oauth2:oauth_urls", uri.getPath());
        List authorities = Convert.toList(String.class, obj);
        authorities = authorities.stream().map(i -> i = "ROLE_" + i).collect(Collectors.toList());
        //认证通过且角色匹配的用户可访问当前路径
        return mono
                .filter(Authentication::isAuthenticated)
                .flatMapIterable(Authentication::getAuthorities)
                .map(GrantedAuthority::getAuthority)
                .any(authorities::contains)
                .map(AuthorizationDecision::new)
                .defaultIfEmpty(new AuthorizationDecision(false));
    }

}
2.5 自定义返回结果:没有登录或token过期时
package top.fate.component;

import cn.hutool.json.JSONUtil;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import top.fate.api.R;
import top.fate.api.ResultCode;

import java.nio.charset.Charset;


@Component
public class RestAuthenticationEntryPoint implements ServerAuthenticationEntryPoint {
    @Override
    public Mono commence(ServerWebExchange exchange, AuthenticationException e) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        String body= JSONUtil.toJsonStr(R.fail(ResultCode.UN_AUTHORIZED.getCode(),ResultCode.UN_AUTHORIZED.getMessage()));
        DataBuffer buffer =  response.bufferFactory().wrap(body.getBytes(Charset.forName("UTF-8")));
        return response.writeWith(Mono.just(buffer));
    }
}
2.6 自定义返回结果:没有权限访问时
package top.fate.component;

import cn.hutool.json.JSONUtil;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import top.fate.api.R;
import top.fate.api.ResultCode;

import java.nio.charset.Charset;


@Component
public class RestAuthenticationEntryPoint implements ServerAuthenticationEntryPoint {
    @Override
    public Mono commence(ServerWebExchange exchange, AuthenticationException e) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        String body= JSONUtil.toJsonStr(R.fail(ResultCode.UN_AUTHORIZED.getCode(),ResultCode.UN_AUTHORIZED.getMessage()));
        DataBuffer buffer =  response.bufferFactory().wrap(body.getBytes(Charset.forName("UTF-8")));
        return response.writeWith(Mono.just(buffer));
    }
}
2.7 网关白名单配置
package top.fate.config;

import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.List;


@Data
@EqualsAndHashCode(callSuper = false)
@Component
@ConfigurationProperties(prefix="secure.ignore")
public class IgnoreUrlsConfig {
    private List urls;
}
2.8 Redis相关配置
package top.fate.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;


@Configuration
@EnableRedisRepositories
public class RedisRepositoryConfig {

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}
2.9 资源服务器配置
package top.fate.config;

import cn.hutool.core.util.ArrayUtil;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.SecurityWebFiltersOrder;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
import org.springframework.security.oauth2.server.resource.authentication.ReactiveJwtAuthenticationConverterAdapter;
import org.springframework.security.web.server.SecurityWebFilterChain;
import reactor.core.publisher.Mono;
import top.fate.authorization.AuthorizationManager;
import top.fate.component.RestAuthenticationEntryPoint;
import top.fate.component.RestfulAccessDeniedHandler;
import top.fate.filter.IgnoreUrlsRemoveJwtFilter;

@AllArgsConstructor
@Configuration
@EnableWebFluxSecurity
public class ResourceServerConfig {
    private final AuthorizationManager authorizationManager;
    private final IgnoreUrlsConfig ignoreUrlsConfig;
    private final RestfulAccessDeniedHandler restfulAccessDeniedHandler;
    private final RestAuthenticationEntryPoint restAuthenticationEntryPoint;
    private final IgnoreUrlsRemoveJwtFilter ignoreUrlsRemoveJwtFilter;

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        http.oauth2ResourceServer().jwt()
                .jwtAuthenticationConverter(jwtAuthenticationConverter());
        //自定义处理JWT请求头过期或签名错误的结果
        http.oauth2ResourceServer().authenticationEntryPoint(restAuthenticationEntryPoint);
        //对白名单路径,直接移除JWT请求头
        http.addFilterBefore(ignoreUrlsRemoveJwtFilter, SecurityWebFiltersOrder.AUTHENTICATION);
        http.authorizeExchange()
                .pathMatchers(ArrayUtil.toArray(ignoreUrlsConfig.getUrls(),String.class)).permitAll()//白名单配置
                .anyExchange().access(authorizationManager)//鉴权管理器配置
                .and().exceptionHandling()
                .accessDeniedHandler(restfulAccessDeniedHandler)//处理未授权
                .authenticationEntryPoint(restAuthenticationEntryPoint)//处理未认证
                .and().csrf().disable();
        return http.build();
    }

    @Bean
    public Converter> jwtAuthenticationConverter() {
        JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
        jwtGrantedAuthoritiesConverter.setAuthorityPrefix("ROLE_");
        jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName("authorities");
        JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
        jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter);
        return new ReactiveJwtAuthenticationConverterAdapter(jwtAuthenticationConverter);
    }

}
2.10 将登录用户的JWT转化成用户信息的全局过滤器
package top.fate.filter;

import cn.hutool.core.util.StrUtil;
import com.nimbusds.jose.JWSObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.text.ParseException;


@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private static Logger LOGGER = LoggerFactory.getLogger(AuthGlobalFilter.class);

    @Override
    public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        if (StrUtil.isEmpty(token)) {
            return chain.filter(exchange);
        }
        try {
            //从token中解析用户信息并设置到Header中去
            String realToken = token.replace("Bearer ", "");
            JWSObject jwsObject = JWSObject.parse(realToken);
            String userStr = jwsObject.getPayload().toString();
            LOGGER.info("AuthGlobalFilter.filter() user:{}",userStr);
            ServerHttpRequest request = exchange.getRequest().mutate().header("user", userStr).build();
            exchange = exchange.mutate().request(request).build();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
2.11 白名单路径访问时需要移除JWT请求头
package top.fate.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import top.fate.config.IgnoreUrlsConfig;

import java.net.URI;
import java.util.List;


@Component
public class IgnoreUrlsRemoveJwtFilter implements WebFilter {
    @Autowired
    private IgnoreUrlsConfig ignoreUrlsConfig;
    @Override
    public Mono filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        URI uri = request.getURI();
        PathMatcher pathMatcher = new AntPathMatcher();
        //白名单路径移除JWT请求头
        List ignoreUrls = ignoreUrlsConfig.getUrls();
        for (String ignoreUrl : ignoreUrls) {
            if (pathMatcher.match(ignoreUrl, uri.getPath())) {
                request = exchange.getRequest().mutate().header("Authorization", "").build();
                exchange = exchange.mutate().request(request).build();
                return chain.filter(exchange);
            }
        }
        return chain.filter(exchange);
    }
}
测试

访问 http://localhost:30001/oauth2-server/oauth/token
密码模式

刷新token

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/922193.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号