2016-01-22 60 views
1

我正在使用Jhipster和Oauth2實現並將mongodb用作數據庫。 我正在嘗試使用OAuth2測試資源。但我總是收到一條錯誤消息「訪問被拒絕」和狀態碼401.我正在尋找OAuth2的JUnit示例。謝謝!如何使用OAuth2和模擬測試資源

曼努埃爾

/** 
* 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))) 
    } 

回答

2

你可以從令牌資源令牌,並使用該令牌在測試中,在這裏一個完整的例子。

@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; 
    } 
} 
相關問題