All Downloads are FREE. Search and download functionalities are using the official Maven repository.

br.com.jhonsapp.bootstrap.test.restTemplate.command.AuthenticationCommand Maven / Gradle / Ivy

package br.com.jhonsapp.bootstrap.test.restTemplate.command;

import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.springframework.boot.json.JacksonJsonParser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import br.com.jhonsapp.bootstrap.test.restTemplate.UserInformation;


public class AuthenticationCommand {

	private UserInformation userInformation;
	
	public AuthenticationCommand() {
		this.userInformation = UserInformation.createUserInformation();
	}
	
	private MultiValueMap createParams(){
		
        MultiValueMap params = new LinkedMultiValueMap();
        params.add("grant_type", "password");
        params.add("client", userInformation.getClient());
        params.add("username", userInformation.getUsername());
        params.add("password", userInformation.getPassword());
		
        return params;
	}
	
	
	public String obtainAccessToken(MockMvc mockMvc) throws Exception {
		
        MultiValueMap params = createParams();
     
        ResultActions result = mockMvc.perform(post("/oauth/token")
        							.params(params)
        							.with(httpBasic(userInformation.getClient(), userInformation.getClientPassword()))
        							.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();
	}
	
	
	public String obtainHeaderAuthorization(MockMvc mockMvc) throws Exception {
		return "Bearer " + obtainAccessToken(mockMvc);
	}

	public UserInformation getUserInformation() {
		return this.userInformation;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy