为了有效地测试资源服务器的安全性,通过
MockMvc和
RestTemplate都可以帮助配置
AuthorizationServerunder
src/test/java:
授权服务器
@Configuration@EnableAuthorizationServer@SuppressWarnings("static-method")class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Bean public JwtAccessTokenConverter accessTokenConverter() throws Exception { JwtAccessTokenConverter jwt = new JwtAccessTokenConverter(); jwt.setSigningKey(SecurityConfig.key("rsa")); jwt.setVerifierKey(SecurityConfig.key("rsa.pub")); jwt.afterPropertiesSet(); return jwt; } @Autowired private AuthenticationManager authenticationManager; @Override public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints .authenticationManager(authenticationManager) .accessTokenConverter(accessTokenConverter()); } @Override public void configure(final ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("myclientwith") .authorizedGrantTypes("password") .authorities("myauthorities") .resourceIds("myresource") .scopes("myscope") .and() .withClient("myclientwithout") .authorizedGrantTypes("password") .authorities("myauthorities") .resourceIds("myresource") .scopes(UUID.randomUUID().toString()); }}集成测试
对于集成测试,您可以简单地使用内置的OAuth2测试支持规则和注释:
@RunWith(SpringJUnit4ClassRunner.class)@SpringApplicationConfiguration(classes = MyApp.class)@WebIntegrationTest(randomPort = true)@OAuth2ContextConfiguration(MyDetails.class)public class MyControllerIT implements RestTemplateHolder { @Value("http://localhost:${local.server.port}") @Getter Stringhost; @Getter @Setter RestOperations restTemplate = new TestRestTemplate(); @Rule public OAuth2ContextSetup context = OAuth2ContextSetup.standard(this); @Test public void testHelloOAuth2WithRole() { ResponseEntity<String> entity = getRestTemplate().getForEntity(host + "/hello", String.class); assertTrue(entity.getStatusCode().is2xxSuccessful()); }}class MyDetails extends ResourceOwnerPasswordResourceDetails { public MyDetails(final Object obj) { MyControllerIT it = (MyControllerIT) obj; setAccessTokenUri(it.getHost() + "/oauth/token"); setClientId("myclientwith"); setUsername("user"); setPassword("password"); }}MockMvc测试 也可以 进行
测试
MockMvc,但需要一个小的帮助程序类来获取一个在请求上
RequestPostProcessor设置
Authorization:Bearer <token>标头的类:
@Componentpublic class OAuthHelper { // For use with MockMvc public RequestPostProcessor bearerToken(final String clientid) { return mockRequest -> { OAuth2AccessToken token = createAccessToken(clientid); mockRequest.addHeader("Authorization", "Bearer " + token.getValue()); return mockRequest; }; } @Autowired ClientDetailsService clientDetailsService; @Autowired AuthorizationServerTokenServices tokenservice; OAuth2AccessToken createAccessToken(final String clientId) { // Look up authorities, resourceIds and scopes based on clientId ClientDetails client = clientDetailsService.loadClientByClientId(clientId); Collection<GrantedAuthority> authorities = client.getAuthorities(); Set<String> resourceIds = client.getResourceIds(); Set<String> scopes = client.getScope(); // Default values for other parameters Map<String, String> requestParameters = Collections.emptyMap(); boolean approved = true; String redirectUrl = null; Set<String> responseTypes = Collections.emptySet(); Map<String, Serializable> extensionProperties = Collections.emptyMap(); // Create request OAuth2Request oAuth2Request = new OAuth2Request(requestParameters, clientId, authorities, approved, scopes, resourceIds, redirectUrl, responseTypes, extensionProperties); // Create OAuth2AccessToken User userPrincipal = new User("user", "", true, true, true, true, authorities); UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userPrincipal, null, authorities); OAuth2Authentication auth = new OAuth2Authentication(oAuth2Request, authenticationToken); return tokenservice.createAccessToken(auth); }}MockMvc然后,您的测试必须
RequestPostProcessor从
OauthHelper类中获取一个,并在发出请求时将其传递:
@RunWith(SpringJUnit4ClassRunner.class)@SpringApplicationConfiguration(classes = MyApp.class)@WebAppConfigurationpublic class MyControllerTest { @Autowired private WebApplicationContext webapp; private MockMvc mvc; @Before public void before() { mvc = MockMvcBuilders.webAppContextSetup(webapp) .apply(springSecurity()) .alwaysDo(print()) .build(); } @Autowired private OAuthHelper helper; @Test public void testHelloWithRole() throws Exception { RequestPostProcessor bearerToken = helper.bearerToken("myclientwith"); mvc.perform(get("/hello").with(bearerToken)).andExpect(status().isOk()); } @Test public void testHelloWithoutRole() throws Exception { RequestPostProcessor bearerToken = helper.bearerToken("myclientwithout"); mvc.perform(get("/hello").with(bearerToken)).andExpect(status().isForbidden()); }}完整的示例项目可在GitHub上找到:https :
//github.com/timtebeek/resource-server-
testing



