feat: gateway增加统一鉴权功能

This commit is contained in:
zlt2000
2023-12-04 17:00:36 +08:00
parent c91f01aea1
commit a9f60ffd34
42 changed files with 1234 additions and 466 deletions
@@ -0,0 +1,57 @@
package com.central.gateway.auth;
import cn.hutool.core.collection.CollectionUtil;
import com.central.common.constant.SecurityConstants;
import com.central.common.model.LoginAppUser;
import com.central.common.utils.LoginUserUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
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.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.security.Principal;
import java.util.Map;
/**
* 认证成功处理类
*
* @author zlt
* @date 2019/10/7
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class Oauth2ServerAuthSuccessHandler implements ServerAuthenticationSuccessHandler {
@Override
public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
MultiValueMap<String, String> headerValues = new LinkedMultiValueMap<>(4);
Object principal = authentication.getPrincipal();
if (principal instanceof OAuth2IntrospectionAuthenticatedPrincipal authenticatedPrincipal) {
Map<String, Object> claims = authenticatedPrincipal.getAttributes();
Authentication auth = (Authentication)claims.get(Principal.class.getName());
LoginAppUser user = LoginUserUtils.getUser(auth);
if (user != null) {
headerValues.add(SecurityConstants.USER_ID_HEADER, String.valueOf(user.getId()));
headerValues.add(SecurityConstants.USER_HEADER, user.getUsername());
}
headerValues.add(SecurityConstants.ROLE_HEADER, CollectionUtil.join(authentication.getAuthorities(), ","));
headerValues.add(SecurityConstants.TENANT_HEADER, (String)claims.get(SecurityConstants.CLIENT_ID));
headerValues.add(SecurityConstants.ACCOUNT_TYPE_HEADER, (String)claims.get(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME));
}
ServerWebExchange exchange = webFilterExchange.getExchange();
ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate()
.headers(h -> h.addAll(headerValues))
.build();
ServerWebExchange build = exchange.mutate().request(serverHttpRequest).build();
return webFilterExchange.getChain().filter(build);
}
}
@@ -0,0 +1,56 @@
package com.central.gateway.auth;
import com.central.common.model.SysMenu;
import com.central.gateway.feign.AsynMenuService;
import com.central.oauth2.common.service.impl.DefaultPermissionServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Future;
/**
* url权限认证
*
* @author zlt
* @date 2019/10/6
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
@Component
public class PermissionAuthManager extends DefaultPermissionServiceImpl implements ReactiveAuthorizationManager<AuthorizationContext> {
@Resource
private AsynMenuService asynMenuService;
@Override
public Mono<AuthorizationDecision> check(Mono<Authentication> authentication, AuthorizationContext authorizationContext) {
return authentication.map(auth -> {
ServerWebExchange exchange = authorizationContext.getExchange();
ServerHttpRequest request = exchange.getRequest();
boolean isPermission = super.hasPermission(auth, request.getMethod().name(), request.getURI().getPath());
return new AuthorizationDecision(isPermission);
}).defaultIfEmpty(new AuthorizationDecision(false));
}
@Override
public List<SysMenu> findMenuByRoleCodes(String roleCodes) {
Future<List<SysMenu>> futureResult = asynMenuService.findByRoleCodes(roleCodes);
try {
return futureResult.get();
} catch (Exception e) {
log.error("asynMenuService.findMenuByRoleCodes-error", e);
}
return Collections.emptyList();
}
}
@@ -0,0 +1,87 @@
package com.central.gateway.config;
import com.central.gateway.auth.*;
import com.central.oauth2.common.component.CustomReactiveAuthorizationServiceIntrospector;
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 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.oauth2.server.resource.web.server.authentication.ServerBearerTokenAuthenticationConverter;
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;
/**
* 资源服务器
*
* @author: zlt
* @date: 2023/11/25
* <p>
* Blog: https://zlt2000.gitee.io
* 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);
});
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)
, SecurityWebFiltersOrder.AUTHENTICATION);
return http.build();
}
private AuthenticationWebFilter getAuthWebFilter(ServerAuthenticationEntryPoint authenticationEntryPoint) {
OpaqueTokenReactiveAuthenticationManager authenticationManager =
new OpaqueTokenReactiveAuthenticationManager(
new CustomReactiveAuthorizationServiceIntrospector());
ServerBearerTokenAuthenticationConverter authenticationConverter = new ServerBearerTokenAuthenticationConverter();
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;
}
}