前面详细说了servlet下资源服务器的配置,gateway中是一样的,只不过api换了。这里直接上代码了。
1. ResourceServerConfig
@Configuration
public class ResourceServerConfig {
@Value("${security.oauth2.ignore_uri:{}}")
private String[] ignoreUriArr;
@Resource
private AuthorizationManager authorizationManager;
@Resource
private RSAKeyPair rsaKeyPair;
@Bean
SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) throws Exception {
// csrf关闭
http.csrf(csrf -> csrf.disable());
// 跨域处理
http.cors(Customizer.withDefaults());
http.httpBasic(httpBasicSpec -> httpBasicSpec.disable());
// 资源服务器配置
http.oauth2ResourceServer(server -> server
// 权限不通过时,自定义返回
.accessDeniedHandler(new MyAccessDeniedHandler())
// 未登录或者登陆验证失败时(token有问题),自定义返回
.authenticationEntryPoint(new MyAuthenticationEntryPoint())
// 使用jwt默认配置
// .jwt(Customizer.withDefaults())
// jwt的自定义校验,设置decoder或者converter
.jwt(jwt ->
jwt
// 当无法提供issuer-uri的时候,可以拿到jwk,包含有私钥
// 可以不在这配置,在decoder中也可以配置从什么地方拿私钥验签
// .jwkSetUri("http://127.0.0.1:9101/oauth2/oauth2/jwks")
.jwtDecoder(jwtDecoder())
// 指定jwt权限验证时的配置:比如 权限使用哪个字段,权限有没有前缀
// .jwtAuthenticationConverter(jwtAuthenticationConverter())
)
);
http.authorizeExchange(exchange ->
exchange
.pathMatchers(ignoreUriArr).permitAll()
.pathMatchers(ignoreFixedUris()).permitAll()
// .anyExchange().authenticated()
// 其他走自定义逻辑
.anyExchange().access(authorizationManager)
);
return http.build();
}
private String[] ignoreFixedUris() {
String[] uriArr = {
// swagger相关
"/gateway/*/v3/api-docs",
"/v3/api-docs/**",
"/swagger-resources/configuration/ui",
"/swagger-resources",
"/swagger-resources/configuration/security",
"/swagger-ui.html",
"/css/**",
"/js/**",
"/images/**",
"/webjars/**",
"/favicon.ico",
"/doc.html",
// admin监控
"/actuator/**",
"/instances/**",
// 登陆相关
"/gateway/oauth2/captcha/get",
"/gateway/oauth2/captcha/check",
"/gateway/oauth2/login/oauthlogin"
};
return uriArr;
}
// private JwtAuthenticationConverter jwtAuthenticationConverter() {
// JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
// JwtGrantedAuthoritiesConverter authoritiesConverter = new JwtGrantedAuthoritiesConverter();
// authoritiesConverter.setAuthoritiesClaimName("perms");
// authoritiesConverter.setAuthorityPrefix("");
// converter.setJwtGrantedAuthoritiesConverter(authoritiesConverter);
// return converter;
// }
// 创建JWT解码器 decoder
private ReactiveJwtDecoder jwtDecoder() {
String publicKeyBase64 = rsaKeyPair.getPublicKeyBase64();
NimbusReactiveJwtDecoder jwtDecoder = NimbusReactiveJwtDecoder.withPublicKey(getPublicKey(publicKeyBase64)).build();
// 使用默认的JWT验证器,主要是过期时间、生效时间(nbf)、X509证书的校验
OAuth2TokenValidator<Jwt> oauth2TokenValidator = new DelegatingOAuth2TokenValidator<>(JwtValidators.createDefault());
jwtDecoder.setJwtValidator(oauth2TokenValidator);
return jwtDecoder;
}
private RSAPublicKey getPublicKey(String publicKeyBase64) {
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyBase64));
RSAPublicKey rsaPublicKey = null;
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
rsaPublicKey = (RSAPublicKey)keyFactory.generatePublic(keySpec);
} catch (Exception e) {
e.printStackTrace();
}
return rsaPublicKey;
}
}
2. 自定义返回
- MyAccessDeniedHandler
@Component
public class MyAccessDeniedHandler implements ServerAccessDeniedHandler {
@Override
public Mono<Void> handle(ServerWebExchange exchange, AccessDeniedException e) {
e.printStackTrace();
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.OK);
response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
String body= JSONUtil.toJsonStr(new Result<String>().bussinessException(CodeMsg.ACCESS_DENY.getCode(), CodeMsg.ACCESS_DENY.getMsg(), e.getMessage()));
DataBuffer buffer = response.bufferFactory().wrap(body.getBytes(Charset.forName("UTF-8")));
return response.writeWith(Mono.just(buffer));
}
}
- MyAuthenticationEntryPoint
@Slf4j
public class MyAuthenticationEntryPoint implements ServerAuthenticationEntryPoint {
@Override
public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException e) {
e.printStackTrace();
ServerHttpResponse response = exchange.getResponse();
Throwable cause = e.getCause();
Result<String> res = new Result<String>().exception(e.getMessage());
try {
if (cause instanceof JwtValidationException) {
if (cause.getMessage().contains("Jwt expired at")) {
String token = exchange.getRequest().getHeaders().getFirst("Authorization").substring(7);
String dateTime = DateUtil.formatDateTime(TokenUtil.getExp(token));
res = new Result<String>().bussinessException(CodeMsg.TOKEN_EXPIRED.getCode(), CodeMsg.TOKEN_EXPIRED.getMsg(), "Jwt expired at " + dateTime);
} else {
res = new Result<String>().error(CodeMsg.TOKEN_INVALID.getCode(), CodeMsg.TOKEN_INVALID.getMsg(), cause.getMessage());
}
} else if (cause instanceof BadJwtException || cause instanceof JwtEncodingException) {
res = new Result<String>().error(CodeMsg.TOKEN_INVALID.getCode(), CodeMsg.TOKEN_INVALID.getMsg(), cause.getMessage());
} else if (cause instanceof InvalidBearerTokenException) {
String token = exchange.getRequest().getHeaders().getFirst("Authorization").substring(7);
String dateTime = DateUtil.formatDateTime(TokenUtil.getExp(token));
res = new Result<String>().bussinessException(CodeMsg.TOKEN_EXPIRED.getCode(), CodeMsg.TOKEN_EXPIRED.getMsg(), "Jwt expired at " + dateTime);
} else {
res = new Result<String>().error(CodeMsg.AUTHENTICATION_FAILED.getCode(), CodeMsg.AUTHENTICATION_FAILED.getMsg(), e.getMessage());
}
} catch (Exception e1) {
log.info(e1.toString());
res = new Result<String>().error(CodeMsg.AUTHENTICATION_FAILED.getCode(), CodeMsg.AUTHENTICATION_FAILED.getMsg(), e.getMessage());
}
response.setStatusCode(HttpStatus.OK);
response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
URI uri = exchange.getRequest().getURI();
// 为了解决token过期时,前端不出现跨域错误,添加了一些header,注意Access-Control-Allow-Origin的值
response.getHeaders().add("Access-Control-Allow-Origin", uri.getScheme() + "://" + uri.getHost());
response.getHeaders().add("Access-Control-Allow-Credentials", "true");
response.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
response.getHeaders().add("Access-Control-Allow-Headers", HttpHeaders.AUTHORIZATION);
String body = JSONUtil.toJsonStr(res);
DataBuffer buffer = response.bufferFactory().wrap(body.getBytes(Charset.forName("UTF-8")));
return response.writeWith(Mono.just(buffer));
}
}
3. 自定义权限校验 AuthorizationManager
/**
* 资源服务的权限管理器
* 鉴权时统一抛出OAuth2AuthorizationException
*/
@Component
public class AuthorizationManager implements ReactiveAuthorizationManager<AuthorizationContext> {
@Resource
private RedisUtil redisUtil;
@Resource
private RSAKeyPair rsaKeyPair;
@Value("${yt.gateway.is_pass:false}")
private boolean isPass;
@Override
public Mono<AuthorizationDecision> check(Mono<Authentication> mono, AuthorizationContext authorizationContext) {
System.out.println("===>>>开始走自定义manager了");
if (isPass) {
return Mono.just(new AuthorizationDecision(true));
}
ServerHttpRequest request = authorizationContext.getExchange().getRequest();
String uri = request.getURI().toString();
// 1. 对应跨域的预检请求直接放行
if (request.getMethod() == HttpMethod.OPTIONS) {
return Mono.just(new AuthorizationDecision(true));
}
// 2. token验证。
/**
* 这个类主要是处理权限(Authorization)的,对于身份(authentication)
* 验证是在 @org.springframework.security.oauth2.server.resource.authentication.JwtReactiveAuthenticationManager
*/
String token = request.getHeaders().getFirst(HDConstant.AUTHORIZATION_KEY);
// 已经做过了decoder,下面这2个判断不会出现错误的
if (StrUtil.isBlank(token)) {
throw new OAuth2AuthorizationException(new OAuth2Error(CodeMsg.USER_NOT_LOGIN.getCode(), CodeMsg.USER_NOT_LOGIN.getMsg(), uri));
}
if (!StrUtil.startWithIgnoreCase(token, "Bearer ")) {
throw new OAuth2AuthorizationException(new OAuth2Error(CodeMsg.TOKEN_INVALID.getCode(), CodeMsg.TOKEN_INVALID.getMsg(), uri));
}
// 3. map中自定义权限校验
return mono
.map(auth -> new AuthorizationDecision(checkAuthorities(token.substring(7), request, auth)))
.defaultIfEmpty(new AuthorizationDecision(false));
}
/**
* 校验权限和client状态
* @param token
* @param request
* @param auth
*/
private boolean checkAuthorities(String token, ServerHttpRequest request, Authentication auth) {
String uri = request.getURI().toString();
// 0. Redis中含有JTI才可用
String jti = TokenUtil.getJti(token);
if (!redisUtil.hasKey(HDConstant.LOGIN_CACHE_KEY_PREFIX + jti + ":token") ) {
throw new OAuth2AuthorizationException(new OAuth2Error(CodeMsg.TOKEN_INVALID.getCode(), CodeMsg.TOKEN_INVALID.getMsg(), uri));
}
// 1. 检查客户端权限范围,暂且定scope为All才算正常client
@SuppressWarnings("unchecked")
Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>) auth.getAuthorities();
List<String> list = authorities.stream().map(e -> e.toString()).collect(Collectors.toList());
if (!list.contains("SCOPE_ALL")) {
throw new OAuth2AuthorizationException(new OAuth2Error(CodeMsg.ACCESS_SCOPE_ERROR.getCode(), CodeMsg.ACCESS_SCOPE_ERROR.getMsg(), uri));
}
// 2. 系统管理员角色直接放行
String rcodes = redisUtil.get(HDConstant.LOGIN_CACHE_KEY_PREFIX + jti + ":rcodes").toString();
if (StrUtil.isBlank(rcodes)) {
throw new OAuth2AuthorizationException(new OAuth2Error(CodeMsg.BUSSINESS_ERROR.getCode(), "无账号缓存角色", uri));
}
if (rcodes.contains(HDConstant.SYSTEM_MANAGER_ROLE_CODE)) {
return true;
}
// 3.权限验证
List<Object> objectList = redisUtil.lGet(HDConstant.LOGIN_CACHE_KEY_PREFIX + jti + ":perms", 0, -1);
List<String> permList = objectList.stream().map(i -> i.toString()).toList();
String path = request.getURI().getPath().substring(8);
if (!permList.contains("gateway:" + path)) {
throw new OAuth2AuthorizationException(new OAuth2Error(CodeMsg.ACCESS_DENY.getCode(), CodeMsg.ACCESS_DENY.getMsg(), uri));
}
return true;
}
}
4. 自定义JwtDecoder校验
/**
* 这个是 配置jwtDecoder用的
* 自定义JWT字段校验,暂时没用
*/
public class MyJwtValidator implements OAuth2TokenValidator<Jwt> {
@Override
public OAuth2TokenValidatorResult validate(Jwt token) {
System.out.println("===>>>开始走自定义decoder了");
// 校验成功,返回
return OAuth2TokenValidatorResult.success();
}
}
5. 公钥的获取
@Component
public class RSAKeyPair {
@Value("${security.token.public_key_base64:null}")
private String publicKeyBase64;
public String getPublicKeyBase64() {
return publicKeyBase64;
}
}
6. Oauth2发生其他异常时捕获
WebFlux版本发生异常时的处理由ErrorWebFluxAutoConfiguration
这个类配置的。主要处理过程在DefaultErrorWebExceptionHandler
类中。返回结果肯定和我们要求的统一样式不一样。我们要重写这2个类。
- GlobalExceptionAutoConfig
/**
* 根据{@link}ErrorWebFluxAutoConfiguration的配置 重写
* 主要是重写errorWebExceptionHandler()的逻辑
* 里面不要DefaultErrorWebExceptionHandler了,用自己写的异常处理类替换
*/
@Configuration(proxyBeanMethods = false)
//@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
//@ConditionalOnClass(WebFluxConfigurer.class)
@AutoConfigureBefore(WebFluxAutoConfiguration.class)
@EnableConfigurationProperties({ ServerProperties.class, WebProperties.class })
public class GlobalExceptionAutoConfig {
private final ServerProperties serverProperties;
public GlobalExceptionAutoConfig(ServerProperties serverProperties) {
this.serverProperties = serverProperties;
}
// 要比 ErrorWebFluxAutoConfiguration 小,表示其优先调用
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
ErrorWebExceptionHandler errorWebExceptionHandler(ErrorAttributes errorAttributes,
WebProperties webProperties, ObjectProvider<ViewResolver> viewResolvers,
ServerCodecConfigurer serverCodecConfigurer, ApplicationContext applicationContext) {
// 使用自定义的异常处理类GlobalExceptionHandler
DefaultErrorWebExceptionHandler exceptionHandler = new GlobalExceptionHandler(errorAttributes,
webProperties.getResources(), this.serverProperties.getError(), applicationContext);
exceptionHandler.setViewResolvers(viewResolvers.orderedStream().collect(Collectors.toList()));
exceptionHandler.setMessageWriters(serverCodecConfigurer.getWriters());
exceptionHandler.setMessageReaders(serverCodecConfigurer.getReaders());
return exceptionHandler;
}
// @Bean
// @ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT)
// public DefaultErrorAttributes errorAttributes() {
// return new DefaultErrorAttributes();
// }
}
- GlobalExceptionHandler
/**
* 异常处理操作,自定义异常中的内容
* 重写了{@link}DefaultErrorWebExceptionHandler部分内容
*/
public class GlobalExceptionHandler extends DefaultErrorWebExceptionHandler {
@Autowired
private GlobalExceptionType globalExceptionType;
public GlobalExceptionHandler(ErrorAttributes errorAttributes, Resources resources,
ErrorProperties errorProperties, ApplicationContext applicationContext) {
super(errorAttributes, resources, errorProperties, applicationContext);
}
/**
* DefaultErrorWebExceptionHandler中是返回页面,这里改成直接返回renderErrorResponse
*/
@Override
protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
}
/**
* 定义renderErrorResponse的body中的内容
*/
@Override
protected Mono<ServerResponse> renderErrorResponse(ServerRequest request) {
// Map<String, Object> error = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
Throwable throwable = getError(request);
return ServerResponse
// .status(super.getHttpStatus(error))
.status(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON)
// .body(BodyInserters.fromValue(new RuntimeException()))
.body(BodyInserters.fromValue(globalExceptionType.handle(throwable)));
}
}
- GlobalExceptionType
/**
* 统一异常
* 主要处理自定义的权限鉴定时的异常,OAuth2AuthorizationException
*/
@Component
public class GlobalExceptionType {
@ExceptionHandler(value = {Exception.class})
public Result<String> handle(Throwable throwable) {
if (throwable instanceof OAuth2AuthorizationException) {
return oAuth2AuthorizationHandle((OAuth2AuthorizationException) throwable);
} else {
throwable.printStackTrace();
return new Result<String>().exception(throwable.getMessage());
}
}
@ExceptionHandler(value = {OAuth2AuthorizationException.class})
public Result<String> oAuth2AuthorizationHandle(OAuth2AuthorizationException e) {
e.printStackTrace();
OAuth2Error error = e.getError();
return new Result<String>().bussinessException(error.getErrorCode(), error.getDescription(), error.getUri());
}
}
主要代码差不多完成。目录结构如下: