栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何测试spring-security-oauth2资源服务器的安全性?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何测试spring-security-oauth2资源服务器的安全性?

为了有效地测试资源服务器的安全性,通过

MockMvc
RestTemplate
都可以帮助配置
AuthorizationServer
under
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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/452686.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号