feat: 抽取通用的资源服务器配置

This commit is contained in:
zlt2000
2023-12-05 23:01:28 +08:00
parent 1d8757c58e
commit 671ab86543
9 changed files with 267 additions and 107 deletions
@@ -16,6 +16,10 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-authorization-server</artifactId>
</dependency>
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-common-core</artifactId>
</dependency>
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>oauth2-oidc-sdk</artifactId>
@@ -0,0 +1,55 @@
package com.central.oauth2.common.component;
import com.central.common.constant.SecurityConstants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.DefaultOAuth2AuthenticatedPrincipal;
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException;
import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector;
import java.security.Principal;
import java.util.Objects;
/**
* 内省 token 解析器
*
* @author: zlt
* @date: 2023/12/5
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
@RequiredArgsConstructor
public class CustomAuthorizationServiceIntrospector implements OpaqueTokenIntrospector {
private final OAuth2AuthorizationService authorizationService;
@Override
public OAuth2AuthenticatedPrincipal introspect(String token) {
OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
if (Objects.isNull(authorization)) {
throw new InvalidBearerTokenException("invalid_token: " + token);
}
// 客户端模式默认返回
if (AuthorizationGrantType.CLIENT_CREDENTIALS.equals(authorization.getAuthorizationGrantType())) {
return new DefaultOAuth2AuthenticatedPrincipal(authorization.getPrincipalName()
, authorization.getAttributes(), AuthorityUtils.NO_AUTHORITIES);
}
String accountType = (String)authorization.getAttributes().get(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME);
Authentication authentication = (Authentication)authorization.getAttributes().get(Principal.class.getName());
OAuth2AuthenticatedPrincipal principal = (OAuth2AuthenticatedPrincipal)authentication.getPrincipal();
principal.getAttributes().put(SecurityConstants.CLIENT_ID, authorization.getRegisteredClientId());
principal.getAttributes().put(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME, accountType);
return principal;
}
}
@@ -16,6 +16,8 @@ import java.security.Principal;
import java.util.*;
/**
* webFlux 内省 token 解析器
*
* @author zlt
* @version 1.0
* @date 2023/12/4
@@ -0,0 +1,84 @@
package com.central.oauth2.common.config;
import cn.hutool.extra.spring.SpringUtil;
import com.central.oauth2.common.component.CustomAuthorizationServiceIntrospector;
import com.central.oauth2.common.component.CustomBearerTokenResolver;
import com.central.oauth2.common.properties.SecurityProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpMethod;
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.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.AuthorizeHttpRequestsConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import javax.annotation.Resource;
/**
* @author zlt
* @version 1.0
* @date 2023/12/5
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@EnableWebSecurity
@Import(BaseSecurityConfig.class)
public class DefaultResourceServerConf {
@Resource
private SecurityProperties securityProperties;
@Resource
private AuthenticationEntryPoint authenticationEntryPoint;
@Resource
private CustomBearerTokenResolver customBearerTokenResolver;
@Resource
private AccessDeniedHandler oAuth2AccessDeniedHandler;
@Bean
public SecurityFilterChain springSecurityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(authorizeRequests -> {
AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizedUrl authorizedUrl = authorizeRequests
.requestMatchers(HttpMethod.OPTIONS).permitAll()
.requestMatchers(securityProperties.getIgnore().getUrls()).permitAll()
.anyRequest();
this.setAuthenticate(authorizedUrl);
}).headers(header -> header
// 避免iframe同源无法登录许iframe
.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin)
).csrf(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED));
// 资源服务配置
http.oauth2ResourceServer(oauth2 -> {
oauth2.authenticationEntryPoint(authenticationEntryPoint)
.bearerTokenResolver(customBearerTokenResolver)
.accessDeniedHandler(oAuth2AccessDeniedHandler)
.opaqueToken(token -> token.introspector(this.getOpaqueTokenIntrospector()));
});
return http.build();
}
protected OpaqueTokenIntrospector getOpaqueTokenIntrospector() {
OAuth2AuthorizationService authorizationService = SpringUtil.getBean(OAuth2AuthorizationService.class);
return new CustomAuthorizationServiceIntrospector(authorizationService);
}
/**
* url权限控制,默认是认证就通过,可以重写实现个性化
*/
protected void setAuthenticate(AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizedUrl authorizedUrl) {
authorizedUrl.authenticated();
}
}
@@ -0,0 +1,116 @@
package com.central.oauth2.common.config;
import com.central.oauth2.common.component.CustomReactiveAuthorizationServiceIntrospector;
import com.central.oauth2.common.component.CustomServerBearerTokenAuthConverter;
import com.central.oauth2.common.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
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.server.resource.authentication.OpaqueTokenReactiveAuthenticationManager;
import org.springframework.security.oauth2.server.resource.introspection.ReactiveOpaqueTokenIntrospector;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.security.web.server.authentication.AuthenticationWebFilter;
import org.springframework.security.web.server.authentication.ServerAuthenticationConverter;
import org.springframework.security.web.server.authentication.ServerAuthenticationEntryPointFailureHandler;
import org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler;
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
import javax.annotation.Resource;
/**
* @author zlt
* @version 1.0
* @date 2023/12/5
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@EnableWebFluxSecurity
@Import(BaseSecurityConfig.class)
public class DefaultWebFluxResourceServerConf {
@Resource
private SecurityProperties securityProperties;
@Resource
private ServerAuthenticationEntryPoint serverAuthenticationEntryPoint;
@Resource
private ServerAccessDeniedHandler serverAccessDeniedHandler;
@Autowired(required = false)
private ReactiveAuthorizationManager authorizationManager;
@Autowired(required = false)
private ServerAuthenticationSuccessHandler successHandler;
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http.csrf(ServerHttpSecurity.CsrfSpec::disable)
.cors(ServerHttpSecurity.CorsSpec::disable)
.headers(hSpec -> hSpec.frameOptions(ServerHttpSecurity.HeaderSpec.FrameOptionsSpec::disable))
.httpBasic(ServerHttpSecurity.HttpBasicSpec::disable)
.exceptionHandling(e -> {
e.authenticationEntryPoint(serverAuthenticationEntryPoint)
.accessDeniedHandler(serverAccessDeniedHandler);
});
http.authorizeExchange(exchange -> {
if (securityProperties.getAuth().getHttpUrls().length > 0) {
exchange.pathMatchers(securityProperties.getAuth().getHttpUrls()).authenticated();
}
if (securityProperties.getIgnore().getUrls().length > 0) {
exchange.pathMatchers(securityProperties.getIgnore().getUrls()).permitAll();
}
exchange.pathMatchers(HttpMethod.OPTIONS).permitAll();
// url 鉴权
if (authorizationManager != null) {
exchange.anyExchange().access(authorizationManager);
} else {
exchange.anyExchange().authenticated();
}
});
http.addFilterAt(this.getAuthWebFilter(), SecurityWebFiltersOrder.AUTHENTICATION);
return http.build();
}
protected AuthenticationWebFilter getAuthWebFilter() {
AuthenticationWebFilter oauth2 = new AuthenticationWebFilter(this.getAuthenticationManager());
oauth2.setServerAuthenticationConverter(this.getAuthenticationConverter());
oauth2.setAuthenticationFailureHandler(this.getFailureHandler());
if (successHandler != null) {
oauth2.setAuthenticationSuccessHandler(successHandler);
}
return oauth2;
}
protected ReactiveAuthenticationManager getAuthenticationManager() {
return new OpaqueTokenReactiveAuthenticationManager(this.getOpaqueTokenIntrospector());
}
protected ServerAuthenticationConverter getAuthenticationConverter() {
CustomServerBearerTokenAuthConverter authenticationConverter =
new CustomServerBearerTokenAuthConverter(securityProperties);
authenticationConverter.setAllowUriQueryParameter(true);
return authenticationConverter;
}
protected ReactiveOpaqueTokenIntrospector getOpaqueTokenIntrospector() {
return new CustomReactiveAuthorizationServiceIntrospector();
}
protected ServerAuthenticationEntryPointFailureHandler getFailureHandler() {
ServerAuthenticationEntryPointFailureHandler failureHandler =
new ServerAuthenticationEntryPointFailureHandler(serverAuthenticationEntryPoint);
failureHandler.setRethrowAuthenticationServiceException(false);
return failureHandler;
}
}
@@ -1,6 +1,7 @@
package com.central.common.utils;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.central.common.constant.SecurityConstants;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.feign.UserService;
@@ -1,34 +0,0 @@
package com.central.common.utils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
/**
* spring获取bean工具类
*
* @author 作者 owen E-mail: 624191343@qq.com
*/
@Order(0)
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;
public static <T> T getBean(Class<T> cla) {
return applicationContext.getBean(cla);
}
public static <T> T getBean(String name, Class<T> cal) {
return applicationContext.getBean(name, cal);
}
public static String getProperty(String key) {
return applicationContext.getBean(Environment.class).getProperty(key);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
SpringUtil.applicationContext = applicationContext;
}
}
@@ -9,6 +9,7 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionAuthenticatedPrincipal;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
@@ -26,6 +27,7 @@ import java.util.Map;
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Component
public class Oauth2ServerAuthSuccessHandler implements ServerAuthenticationSuccessHandler {
@Override
public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
@@ -1,24 +1,8 @@
package com.central.gateway.config;
import com.central.gateway.auth.*;
import com.central.oauth2.common.component.CustomReactiveAuthorizationServiceIntrospector;
import com.central.oauth2.common.component.CustomServerBearerTokenAuthConverter;
import com.central.oauth2.common.config.BaseSecurityConfig;
import com.central.oauth2.common.properties.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import com.central.oauth2.common.config.DefaultWebFluxResourceServerConf;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpMethod;
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.server.resource.authentication.OpaqueTokenReactiveAuthenticationManager;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.security.web.server.authentication.AuthenticationWebFilter;
import org.springframework.security.web.server.authentication.ServerAuthenticationEntryPointFailureHandler;
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
/**
* 资源服务器
@@ -30,60 +14,6 @@ import org.springframework.security.web.server.authorization.ServerAccessDeniedH
* Github: https://github.com/zlt2000
*/
@Configuration
@EnableWebFluxSecurity
@Slf4j
@Import(BaseSecurityConfig.class)
public class ResourceServerConfiguration {
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http
, SecurityProperties securityProperties, PermissionAuthManager permissionAuthManager
, ServerAuthenticationEntryPoint authenticationEntryPoint, ServerAccessDeniedHandler accessDeniedHandler) {
http.csrf(ServerHttpSecurity.CsrfSpec::disable)
.cors(ServerHttpSecurity.CorsSpec::disable)
.headers(hSpec -> hSpec.frameOptions(ServerHttpSecurity.HeaderSpec.FrameOptionsSpec::disable))
.httpBasic(ServerHttpSecurity.HttpBasicSpec::disable)
.exceptionHandling(e -> {
e.authenticationEntryPoint(authenticationEntryPoint)
.accessDeniedHandler(accessDeniedHandler);
});
public class ResourceServerConfiguration extends DefaultWebFluxResourceServerConf {
http.authorizeExchange(exchange -> {
if (securityProperties.getAuth().getHttpUrls().length > 0) {
exchange.pathMatchers(securityProperties.getAuth().getHttpUrls()).authenticated();
}
if (securityProperties.getIgnore().getUrls().length > 0) {
exchange.pathMatchers(securityProperties.getIgnore().getUrls()).permitAll();
}
exchange.pathMatchers(HttpMethod.OPTIONS).permitAll()
.anyExchange().access(permissionAuthManager);
});
http.addFilterAt(this.getAuthWebFilter(authenticationEntryPoint, securityProperties)
, SecurityWebFiltersOrder.AUTHENTICATION);
return http.build();
}
private AuthenticationWebFilter getAuthWebFilter(ServerAuthenticationEntryPoint authenticationEntryPoint
, SecurityProperties securityProperties) {
OpaqueTokenReactiveAuthenticationManager authenticationManager =
new OpaqueTokenReactiveAuthenticationManager(
new CustomReactiveAuthorizationServiceIntrospector());
CustomServerBearerTokenAuthConverter authenticationConverter =
new CustomServerBearerTokenAuthConverter(securityProperties);
authenticationConverter.setAllowUriQueryParameter(true);
AuthenticationWebFilter oauth2 = new AuthenticationWebFilter(authenticationManager);
oauth2.setServerAuthenticationConverter(authenticationConverter);
oauth2.setAuthenticationFailureHandler(getFailureHandler(authenticationEntryPoint));
oauth2.setAuthenticationSuccessHandler(new Oauth2ServerAuthSuccessHandler());
return oauth2;
}
private ServerAuthenticationEntryPointFailureHandler getFailureHandler(ServerAuthenticationEntryPoint authenticationEntryPoint) {
ServerAuthenticationEntryPointFailureHandler failureHandler =
new ServerAuthenticationEntryPointFailureHandler(authenticationEntryPoint);
failureHandler.setRethrowAuthenticationServiceException(false);
return failureHandler;
}
}