gpt4 book ai didi

java - 如何使用 Spring Security 模拟身份验证和授权

转载 作者:行者123 更新时间:2023-12-01 20:20:02 34 4
gpt4 key购买 nike

我有一个 spring-boot REST API 应用程序。 REST 端点受 spring-security 保护。

这是spring-security的配置:

protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.exceptionHandling().authenticationEntryPoint(new CustomForbiddenErrorHandler())
.and()

.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()

.authorizeRequests()
.antMatchers("/api/**").authenticated() // HTTP 403 if the request is not authenticated
.antMatchers("/**").permitAll();
}

效果很好。如果我在 HTTP header 上没有身份验证 token 的情况下进行休息调用,我会返回正确的 HTTP 错误代码。

如果未按顺序提供,我可以强制 spring 以某种方式添加 self 身份验证 token ,以便我可以在没有自己的访问管理系统的情况下进行 REST 调用吗?稍后将安装。

我不是问如何编写 JUnit 测试。我要问的是如何动态生成模拟身份验证 token 并将其添加到请求(如果不存在)。

最佳答案

您可以覆盖现有的身份验证过滤器,或创建新的自定义过滤器,以检查请求是否包含不记名 token 。根据结果​​,您可以按原样处理请求,也可以使用自定义身份验证对象来扩充请求。

查看OAuth2AuthenticationProcessingFilter ,这会从传入请求中提取 OAuth2 token ,并使用它来填充 Spring Security 上下文。您可以覆盖其行为或创建一个新的过滤器,用您的模拟身份验证对象填充安全上下文。

以下是帮助您入门的示例代码:

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
boolean debug = logger.isDebugEnabled();
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)res;

try {
Authentication authentication = this.tokenExtractor.extract(request);
if (Objects.isNull(authentication)) {
final UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken("username", "password");

authenticationToken.setDetails(Collections.singletonMap("user_uuid", userUuid.toString()));

final OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(null, authenticationToken);

// You can either ask your authenticatoin manager to authenticate these credentials or directly publish auth success event with your mock auth object.

this.eventPublisher.publishAuthenticationSuccess(oAuth2Authentication);
SecurityContextHolder.getContext().setAuthentication(oAuth2Authentication);

} else {
request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, authentication.getPrincipal());
if (authentication instanceof AbstractAuthenticationToken) {
AbstractAuthenticationToken needsDetails = (AbstractAuthenticationToken)authentication;
needsDetails.setDetails(this.authenticationDetailsSource.buildDetails(request));
}

Authentication authResult = this.authenticationManager.authenticate(authentication);
if (debug) {
logger.debug("Authentication success: " + authResult);
}

this.eventPublisher.publishAuthenticationSuccess(authResult);
SecurityContextHolder.getContext().setAuthentication(authResult);
}

关于java - 如何使用 Spring Security 模拟身份验证和授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58940275/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com