- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我已经花了整整几天时间试图弄清楚我做错了什么,但不知道为什么它不起作用。首先,我想说的是,以下配置主要是从我正在处理的另一个项目中复制而来的,并且这些项目可以毫无问题地运行(但是它们的配置略有不同,并且使用的是较旧的 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...>
@WithMockUser
测试不会导致异常,但是由于我正在测试身份验证 Controller ,因此我不能使用此注释(当然,在生产模式下也是不可能的)。
@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;
}
}
@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);
}
}
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);
}
}
@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());
}
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/
我是一名优秀的程序员,十分优秀!