这是一个使用MVC控制器的Spring Boot 2.0.6应用程序,该控制器使用@PreAuthorize和#oauth2.hasScope来保护控制器端点。我已经使用@WebMvcTest编写了编写控制器测试的测试。似乎正在发出请求,但是在调用#oauth2.hasScope
时,它没有提供可与某个地方进行比较的值。我有什么问题?
例外
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: Failed to evaluate expression '#oauth2.hasScope('foo')'
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:71)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:166)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
...
Caused by: java.lang.IllegalArgumentException: Failed to evaluate expression '#oauth2.hasScope('eq.distributor')'
at org.springframework.security.access.expression.ExpressionUtils.evaluateAsBoolean(ExpressionUtils.java:30)
at org.springframework.security.access.expression.method.ExpressionBasedPreInvocationAdvice.before(ExpressionBasedPreInvocationAdvice.java:59)
at org.springframework.security.access.prepost.PreInvocationAuthorizationAdviceVoter.vote(PreInvocationAuthorizationAdviceVoter.java:72)
... 72 more
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1011E: Method call: Attempted to call method hasScope(java.lang.String) on null context object
at org.springframework.expression.spel.ast.MethodReference.throwIfNotNullSafe(MethodReference.java:153)
at org.springframework.expression.spel.ast.MethodReference.getValueRef(MethodReference.java:82)
... 94 more
测试课程
@RunWith(SpringRunner.class)
@WebMvcTest
public class MockMvcTestBase {
@Autowired
protected WebApplicationContext context;
private ObjectMapper objectMapper;
private MockMvc mockMvc;
@Before
public void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
.apply(documentationConfiguration(this.restDocumentation)
.uris()
.withScheme("http")
.withHost("development.com")
.withPort(80))
.alwaysDo(document("{method-name}", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint())))
.apply(springSecurity())
.build();
this.objectMapper = new ObjectMapper();
}
@Test
@WithMockUser(username = "testclient", authorities = "foo")
public void givenValidUser_whenGetOrderDetailsWebEC_thenGetOrder() throws Exception {
getMockMvc().perform(get("/ok")
.header("Authorization", authorizationHeader()))
.andExpect(status().isOk())
.andExpect(content().string("ok"));
}
}
身份验证配置
@Configuration
@EnableAuthorizationServer
@EnableWebSecurity(debug = true)
@EnableGlobalMethodSecurity(prePostEnabled = true)
@SuppressWarnings("static-method")
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Bean
public static PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
@Override
public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("testclient")
.secret("password")
.authorizedGrantTypes("client_credentials")
.accessTokenValiditySeconds(0)
.scopes("foo")
.and()
.withClient("bar")
.secret("password")
.authorizedGrantTypes("client_credentials")
.accessTokenValiditySeconds(0)
.scopes("eq.distributor");
}
}
控制器
@PreAuthorize("#oauth2.hasScope('foo')")
@RequestMapping(value = "/ok", method = RequestMethod.GET)
public String ok() {
return "ok";
}
Spring Security调试输出
org.springframework.mock.web.MockHttpServletRequest@54704b46
servletPath:
pathInfo:/ok
headers:
Authorization: Bearer 57962883-e379-433b-b613-1f888471fb84
Accept: application/json;charset=UTF-8
Security filter chain: [
WebAsyncManagerIntegrationFilter
SecurityContextPersistenceFilter
HeaderWriterFilter
LogoutFilter
OAuth2AuthenticationProcessingFilter
RequestCacheAwareFilter
SecurityContextHolderAwareRequestFilter
AnonymousAuthenticationFilter
SessionManagementFilter
ExceptionTranslationFilter
FilterSecurityInterceptor
]
任何有关我在设置中缺少的内容的帮助都将非常有帮助。似乎确实有问题,好像它实际上是在尝试进行身份验证时,将返回401/403。也不例外。减去进行此编译所需的更改,此更改在Spring Boot 1.5.9下有效。
如果我换出@SpringBootTest的模拟mvc注释,这可以工作,但是我不需要这些测试中的数据库,因此我想将其设置为不需要加载它。
答案 0 :(得分:0)
发生这种情况是因为Spring正在使用DefaultMethodSecurityExpressionHandler
。
看到这个:#oauth2 security expressions on method level
要解决此问题,请执行以下操作:
@EnableGlobalMethodSecurity
删除AuthorizationServerConfig
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class MethodSecurityConfiguration extends GlobalMethodSecurityConfiguration {
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
return new OAuth2MethodSecurityExpressionHandler();
}
}
对我来说重要的是,我已经在其他配置上已经使用了@EnableGlobalMethodSecurity
,所以spring最初忽略了新的配置类