如何使用OAuth2和Mock测试资源

时间:2016-01-22 15:46:30

标签: spring oauth-2.0 spring-security-oauth2 jhipster

我使用Jhipster和Oauth2实现,mongodb作为数据库。 我正在尝试使用OAuth2测试资源。但我总是收到一条错误消息“Access Denied”和状态码401.我正在寻找一个带有OAuth2的JUnit示例。谢谢!

曼努埃尔

 /**
 * Test class for the InvoiceResource REST controller.
 *
 * @see InvoiceResource
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest
public class InvoiceResourceIntTest {
...
private MockMvc restInvoiceMockMvcWebApp;

    @PostConstruct
    public void setup() {
       MockitoAnnotations.initMocks(this);
       this.restInvoiceMockMvcWebApp = MockMvcBuilders.webAppContextSetup(context).alwaysDo(MockMvcResultHandlers.print())
        .apply(SecurityMockMvcConfigurers.springSecurity()).build();
    }

    @Before
    public void initTest() {
        // Create currentuser
        currentUser = new User();
        currentUser.setActivated(CURRENTUSER_ACTIVATED);
        currentUser.setFirstName(CURRENTUSER_FIRSTNAME);
        currentUser.setLastName(CURRENTUSER_LASTNAME);
        currentUser.setEmail(CURRENTUSER_EMAIL);

        Set<Authority> authorities = new HashSet<>();
        Authority authority = new Authority();
        authority.setName(AuthoritiesConstants.ADMIN);
        currentUser.setAuthorities(authorities);
        currentUser.setPassword(passwordEncoder.encode(CURRENTUSER_PASSWORD));
        userRepository.save(currentUser);
    }

    @Test
    // @WithMockUser(username = CURRENTUSER_EMAIL, password = CURRENTUSER_PASSWORD, roles = { "ADMIN" })
    public void getAllInvoices() throws Exception {
        // Initialize the database
        invoice.setDeletedAt(LocalDate.now());
        invoiceRepository.save(invoice);

        invoice.setId(null);
        invoice.setDeletedAt(null);
        invoiceRepository.save(invoice);

        // Get all the invoices
        restInvoiceMockMvcWebApp.perform(get("/api/invoicessort=id,desc")
          .with(user(CURRENTUSER_EMAIL).password(CURRENTUSER_PASSWORD.roles("ADMIN")))
          .andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON)).andExpect(jsonPath("$", hasSize(1)))
     }

1 个答案:

答案 0 :(得分:3)

您可以从令牌资源中获取令牌,并在测试中使用该令牌,这是一个完整的示例。

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
public class PermissionTest {

    @Autowired
    WebApplicationContext context;
    @Autowired
    FilterChainProxy springSecurityFilterChain;
    MockMvc mvc;

    @Before
    public void setUp() {
        mvc = MockMvcBuilders.webAppContextSetup(context)
                .addFilter(springSecurityFilterChain).build();
    }

    @Test
    public void shouldHavePermission() throws Exception {
        mvc.perform(get("/api/resource")
                .header("Authorization", "Bearer " + getAccessToken("user", "123"))
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());
    }

    private String getAccessToken(String username, String password) {    
        MockHttpServletResponse response = mvc
                .perform(post("/oauth/token")
                        .header("Authorization", "Basic "
                                + new String(Base64Utils.encode(("appclient:password")
                                .getBytes())))
                        .param("username", username)
                        .param("password", password)
                        .param("grant_type", "password"))
                .andReturn().getResponse();

        return new ObjectMapper()
                .readValue(response.getContentAsByteArray(), OAuthToken.class)
                .accessToken;
    }


    @JsonIgnoreProperties(ignoreUnknown = true)
    private static class OAuthToken {
        @JsonProperty("access_token")
        public String accessToken;
    }
}