Created
July 2, 2019 14:55
-
-
Save bennettdams/164f4cb4277a8b73529ef2e6c257de88 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Helper method to create an OAuth2 access token via MockMvc. | |
* Result is a string that can be used in another mvc request. | |
* Example: | |
* <p> | |
* MvcResult result = mvc.perform(get("/user/" + userToSearch.getUsername() + "/role") | |
* .header("Authorization", "Bearer " + accessToken)) | |
* .andExpect(status().isOk()) | |
* .andReturn(); | |
* | |
* @param username Username of the token requester. | |
* @param password Password of the token requester. | |
* @return String of the access token. | |
* @author Bennett Dams | |
*/ | |
private String obtainAccessToken(String username, String password) throws Exception { | |
MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); | |
params.add("grant_type", "password"); | |
params.add("client_id", "emiclient"); | |
params.add("username", username); | |
params.add("password", password); | |
ResultActions result | |
= mvc.perform(post("/oauth/token") | |
.params(params) | |
.with(httpBasic("emiclient", "password")) | |
.accept("application/json;charset=UTF-8")) | |
.andExpect(status().isOk()) | |
.andExpect(content().contentType("application/json;charset=UTF-8")); | |
String resultString = result.andReturn().getResponse().getContentAsString(); | |
JacksonJsonParser jsonParser = new JacksonJsonParser(); | |
return jsonParser.parseMap(resultString).get("access_token").toString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment