gpt4 book ai didi

spring - 如何使用 OAuth2 和 Mock 测试资源

转载 作者:行者123 更新时间:2023-12-02 04:14:02 28 4
gpt4 key购买 nike

我使用带有 Oauth2 实现的 Jhipster 和 mongodb 作为数据库。我正在尝试使用 OAuth2 测试资源。但我总是收到错误消息“访问被拒绝”和状态代码 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)))
}

最佳答案

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

@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;
}
}

关于spring - 如何使用 OAuth2 和 Mock 测试资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34950565/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com