gpt4 book ai didi

spring - 在没有 @WithMockUser 的情况下,无法在 Spring Boot 应用程序中摆脱 "An Authentication object was not found in the SecurityContext"

转载 作者:行者123 更新时间:2023-12-04 15:08:00 26 4
gpt4 key购买 nike

我已经花了整整几天时间试图弄清楚我做错了什么,但不知道为什么它不起作用。首先,我想说的是,以下配置主要是从我正在处理的另一个项目中复制而来的,并且这些项目可以毫无问题地运行(但是它们的配置略有不同,并且使用的是较旧的 Spring/Spring Boot 版本)。我不能提供更少的代码,因为我认为这些类配置错误,并且我无法在以下配置类中看到拼写错误或其他任何内容。我很想从头开始重写,但这次不行。 (名称以 I 开头的组件是我的,不是 Spring Framework 的一部分)。

所以这里的异常(exception)是:

org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:379) ~[spring-security-core-4.2.1.RELEASE.jar:4.2.1.RELEASE]
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:223) ~[spring-security-core-4.2.1.RELEASE.jar:4.2.1.RELEASE]
at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:65) ~[spring-security-core-4.2.1.RELEASE.jar:4.2.1.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:656) ~[spring-aop-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at FOO.BAR.AuthenticationController$$EnhancerBySpringCGLIB$$b4949cda.getSelf(<generated>) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_65]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_65]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_65]
at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_65]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:220) ~[spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134) ~[spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622) ~[tomcat-embed-core-8.5.6.jar:8.5.6]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) ~[tomcat-embed-core-8.5.6.jar:8.5.6]
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at FOO.BAR.AbstractControllerTest.get(AbstractControllerTest.java:55) [web-test-0-SNAPSHOT.jar:na]
at FOO.BAR.AuthenticationControllerOkTest.testAuthenticate(AuthenticationControllerOkTest.java:31) [test-classes/:na]
<...JUnit stuff...>

我在网上找到的唯一类似的问题是 this one .但如果我没记错的话,它似乎描述了一个稍微不同的情况。毫无值(value),当然:添加 @WithMockUser测试不会导致异常,但是由于我正在测试身份验证 Controller ,因此我不能使用此注释(当然,在生产模式下也是不可能的)。

AbstractCustomTypesGlobalMethodSecurityConfiguration

这是我用来向 @PreAuthorize 添加一些自定义类型支持的样板类。 .我认为这很容易,而且这个看起来并不可疑:

public abstract class AbstractCustomTypesGlobalMethodSecurityConfiguration
extends GlobalMethodSecurityConfiguration {

@Nonnull
protected abstract ApplicationContext applicationContext();

@Nonnull
protected abstract ConversionService conversionService();

@Nonnull
protected abstract PermissionEvaluator permissionEvaluator();

@Nonnull
@SuppressWarnings("DesignForExtension")
protected Object filter(@Nonnull final MethodSecurityExpressionHandler handler, @Nonnull final Object filterTarget,
@Nonnull final Expression filterExpression, @Nonnull final EvaluationContext context) {
return handler.filter(filterTarget, filterExpression, context);
}

@Override
protected final MethodSecurityExpressionHandler createExpressionHandler() {
final ApplicationContext applicationContext = applicationContext();
final TypeConverter typeConverter = new StandardTypeConverter(conversionService());
final DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler() {
@Override
public StandardEvaluationContext createEvaluationContextInternal(final Authentication authentication, final MethodInvocation methodInvocation) {
final StandardEvaluationContext decoratedStandardEvaluationContext = super.createEvaluationContextInternal(authentication, methodInvocation);
return new ForwardingStandardEvaluationContext() {
@Override
protected StandardEvaluationContext standardEvaluationContext() {
return decoratedStandardEvaluationContext;
}

@Override
public TypeConverter getTypeConverter() {
return typeConverter;
}
};
}

@Override
public Object filter(final Object filterTarget, final Expression filterExpression, final EvaluationContext context) {
return AbstractCustomTypesGlobalMethodSecurityConfiguration.this.filter(this, filterTarget, filterExpression, context);
}
};
handler.setApplicationContext(applicationContext);
handler.setPermissionEvaluator(permissionEvaluator());
return handler;
}

}

安全配置

基本上,以下配置只是扩展了后者的配置,使用模板方法设计模式提供所需的 bean。没什么可疑的,我猜除了 @EnableGlobalMethodSecurity ,但是注释似乎起作用并且启用/禁用其标志也会影响整体行为。 (将注释移动到另一个配置也不起作用,因为它可能适用于某些情况。)

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
class SecurityConfiguration
extends AbstractCustomTypesGlobalMethodSecurityConfiguration {

@Autowired
private ApplicationContext applicationContext;

@Autowired
private ConversionService conversionService;

@Nonnull
@Override
protected ApplicationContext applicationContext() {
return applicationContext;
}

@Nonnull
@Override
protected ConversionService conversionService() {
return conversionService;
}

@Nonnull
@Override
protected final PermissionEvaluator permissionEvaluator() {
return getAlwaysPermittedPermissionEvaluator();
}

@Nonnull
@Override
protected final Object filter(@Nonnull final MethodSecurityExpressionHandler handler, @Nonnull final Object filterTarget,
@Nonnull final Expression filterExpression, @Nonnull final EvaluationContext context) {
final MethodSecurityExpressionOperations operations = (MethodSecurityExpressionOperations) context.getRootObject().getValue();
operations.setFilterObject(filterTarget);
return filterExpression.getValue(context, Object.class);
}

}

网络安全配置

或多或少是微不足道的 Web 安全配置,它定义了一些访问服务端点的规则。请注意,过滤器“beaned”为 authenticationTokenProcessingFilter没有被调用,因为异常首先发生。

@Configuration
@EnableWebSecurity
class WebSecurityConfiguration
extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService userDetailsService;

@Autowired
private ITokenAuthenticationService tokenAuthenticationService;

@Override
protected final void configure(final HttpSecurity httpSecurity)
throws Exception {
httpSecurity
.authorizeRequests()
.antMatchers(POST, "/api/v0/authentication").permitAll()
.antMatchers("/api/v0/**").fullyAuthenticated()
.antMatchers("/**").permitAll();
httpSecurity
.csrf().disable()
.httpBasic()
.authenticationEntryPoint(customAuthenticationEntryPoint());
httpSecurity
.sessionManagement()
.sessionCreationPolicy(STATELESS);
httpSecurity
.addFilterBefore(authenticationTokenProcessingFilter(), UsernamePasswordAuthenticationFilter.class);
}

@Bean
AuthenticationEntryPoint customAuthenticationEntryPoint() {
return getCustomAuthenticationEntryPoint();
}

@Bean
GenericFilterBean authenticationTokenProcessingFilter() {
return getAuthenticationTokenProcessingFilter(tokenAuthenticationService);
}

@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

@Autowired
void registerGlobalAuthentication(final AuthenticationManagerBuilder managerBuilder)
throws Exception {
managerBuilder
.userDetailsService(userDetailsService)
.and()
.eraseCredentials(false);
}

}

我认为这几乎是完整的代码,可能需要诊断。它看起来并没有损坏,但我仍然无法弄清楚我为什么会出现异常的原因。我开始觉得我的头发变白了。

任何帮助是极大的赞赏!

依赖项:
  • org.springframework.boot:spring-boot-dependencies:1.4.3.RELEASE:pom
  • org.springframework.boot:spring-boot-starter-web:1.4.3.RELEASE
  • org.springframework.security:spring-security-config:4.2.1.RELEASE
  • org.springframework.security:spring-security-core:4.2.1.RELEASE
  • org.springframework.security:spring-security-web:4.2.1.RELEASE

  • 编辑 1

    @Test
    @DatabaseSetup(DATASET)
    // @WithMockUser is commented out -- we're authenticating as Alice ourselves to obtain the authentication token
    public void testAuthenticate()
    throws Exception {
    final MockHttpServletResponse response = post("/authentication", asJson(), identityWithKeyGsonIncomingDto("Alice", "alice123"))
    // Here is where it fails: the exception causes HTTP 500 rather than HTTP 201
    .andExpect(status().isCreated())
    .andReturn()
    .getResponse();
    @SuppressWarnings("unchecked")
    final Map<String, Object> responseMap = gson.fromJson(response.getContentAsString(), Map.class);
    final String token = (String) responseMap.get("token");
    get("/users/self", headers("Authorization", token))
    .andExpect(status().isOk());
    }

    编辑 2

    public final class AuthenticationTokenProcessingFilter
    extends GenericFilterBean {

    ...

    @Override
    public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
    throws IOException, ServletException {
    @Nullable
    final String authenticationToken = getAuthenticationToken(request);
    if ( authenticationToken != null ) {
    try {
    final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    final Authentication authentication = tokenAuthenticationService.authenticate(authenticationToken, httpServletRequest);
    setCurrentAuthentication(authentication);
    } catch ( final AuthenticationException ex ) {
    ...
    }
    }
    chain.doFilter(request, response);
    }

    }

    不幸的是,异常发生在上面的过滤器由于某种原因可以控制之前。请注意,此过滤器旨在仅在某些情况下设置当前用户身份验证,但绝不会 - 匿名。至少这是它在我的其他模块中的工作方式。

    最佳答案

    很抱歉,我提供的大量代码并未揭示问题的真正原因。在对其进行了更多实验之后,我被建议在生产模式下运行用例(由于首先进行了测试,我完全忘记了它),并且它在生产模式下运行没有任何问题。缩小到测试范围,我首先检查了测试注释以确保它具有所有注释,包括 @WithSecurityContextTestExecutionListener就像其他模块一样。然后我发现我错过了一个非常关键的事情:听众可以影响的最小范围是单个测试,并且可能是模拟的 MVC 对象( MockMvc 我没有包含在原始问题中,因为我相信它只是配置问题)没有配置好。是的,MockMvc实例以下列方式初始化(​​测试父类(super class)之一中的 @Before 方法):

    mvc = webAppContextSetup(webApplicationContext)
    .build();

    这就是为什么它对我不起作用,因为 MockMvc实例也必须配置。

    mvc = webAppContextSetup(webApplicationContext)
    .apply(springSecurity()) // this is the key
    .build();

    一个不相信“注释可以自己做你需要的一切”的好例子。不幸的是,我浪费了很多时间,但我很高兴我终于找到了原因。

    关于spring - 在没有 @WithMockUser 的情况下,无法在 Spring Boot 应用程序中摆脱 "An Authentication object was not found in the SecurityContext",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43008149/

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