Spring security oAuth2模拟测试

时间:2017-02-22 21:11:38

标签: spring unit-testing spring-boot spring-oauth2

我有一个休息控制器,需要用户进行身份验证。但是当测试运行时,响应总是为401.我正在使用" WithSecurityContext"注释,但它不起作用。

注释

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='kDropdown' style="background-color: black; height: 100px; width: 100px;"></div>

<div class="hide_k hidden-dropdown">
  <ul>
    <li>LIST</li>
    <li>THAT</li>
    <li>IS</li>
    <li>HIDDEN</li>
  </ul>
</div>

实施注释的类

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD })
@WithSecurityContext(factory = WithOAuth2AuthenticationSecurityContextFactory.class)
public @interface WithOAuth2Authentication {

    String clientId() default "temporal";

    String username() default "username";

    String[] scopes() default { "read", "write", "trust" };
}

单元测试

public class WithOAuth2AuthenticationSecurityContextFactory implements WithSecurityContextFactory<WithOAuth2Authentication> {

     @Override
     public SecurityContext createSecurityContext(WithOAuth2Authentication annotation) {
         Set<String> scopes = new HashSet<>();
         Collections.addAll(scopes, annotation.scopes());

         OAuth2Request oAuth2Request = new OAuth2Request(null, annotation.clientId(), null, true, scopes, null, null, null, null);
         Authentication auth2Authentication = new OAuth2Authentication(oAuth2Request, new TestingAuthenticationToken(annotation.username(), null, "read"));

         SecurityContext context = SecurityContextHolder.createEmptyContext();
         context.setAuthentication(auth2Authentication);
         return context;
     }
}

测试结果

    @Before
    public void setup() {
        this.mapper = new ObjectMapper();
        RestDocumentationResultHandler document =
        document("{method-name}", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()));

        this.mock = MockMvcBuilders.webAppContextSetup(this.context)
            .apply(documentationConfiguration(this.restDocumentation))
            .apply(SecurityMockMvcConfigurers.springSecurity())
            .alwaysDo(document)
            .build();
    }

    @Test
    @WithOAuth2Authentication
    public void create() throws Exception {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Accept-Language", "en");
        httpHeaders.add("Content-Type", "application/json");
        httpHeaders.add("Accept", "application/json");

        String JSON = this.mapper.writeValueAsString(new Register.Project());
        this.mock.perform(post("/project/create")
            .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
            .headers(httpHeaders)
            .content(JSON))
            .andDo(print())
            .andExpect(status().isOk());
}

0 个答案:

没有答案