Confidential clients are not permitted to use the request body when authenticating? - access-token

I am using google oauth java client for getting the access token using authorization code. I am getting the above error not sure what's wrong. Here is the code i am using
TokenResponse response = new AuthorizationCodeTokenRequest(
new NetHttpTransport(), new JacksonFactory(),
new GenericUrl(TOKEN_END_POINT), authorizationCode
)
.setRedirectUri(REDIRECT_URI)
.setClientAuthentication(new ClientParametersAuthentication(CLIENT_ID, CLIENT_SECRET))
.execute();

I finally found the answer after struggling a lot. Nearly it took 1 day to find the answer. Here is the solution.
final String encString = Base64.getEncoder().encodeToString((clientId+":"+clientSecret).getBytes());
TokenResponse response = new AuthorizationCodeTokenRequest(
new NetHttpTransport(), new JacksonFactory(),
new GenericUrl(TOKEN_ENDPOINT), authorizationCode
)
.setRequestInitializer(new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
request.getHeaders().setAuthorization("Basic "+encString);
}
})
.setRedirectUri(REDIRECT_URI)
.execute();

Related

How to get response from DHL Api to browser

i have problem with api from dhl, i create GET api from dhl, when print in console, result will print, but when using browser i got response like this :
com.squareup.okhttp.internal.http.RealResponseBody#68bd3d26
this my code :
#RequestMapping("/getData")
public String getAcc() throws IOException
{
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
HttpUrl httpUrl = new HttpUrl.Builder()
.scheme("https")
.host("api-eu.dhl.com")
.addPathSegment("track")
.addPathSegment("shipments")
.addQueryParameter("trackingNumber", "cencored")
.addQueryParameter("service", "express")
.build();
Request request = new Request.Builder()
.addHeader("content-type", "application/json")
.addHeader("Connection", "close")
.addHeader("DHL-API-Key", "cencored")
.addHeader("ConsumerKey", "cencored")
.addHeader("ConsumerSecret", "cencored")
.removeHeader("Content-Encoding")
.removeHeader("Content-Length")
.url(httpUrl) // <- Finally put httpUrl in here
.build();
response = client.newCall(request).execute();
System.out.println(response.body().string());
return this.response.body().toString();
}
solved...
this is weird, but work for me.
so we can't call "response.body().string();" twice.
This is the correctly way to consume a soap webservice with spring boot: https://spring.io/guides/gs/consuming-web-service/
Follow this tutorial and it works fine.

Service that checks if token hasnt expired

so I have a authentication bean which provides access tokens from client credentials.
public class AuthServiceBean {
#Value("${some.url}")
private String someUrl;
#Value("${some.clientId}")
private String someClientId;
#Value("${some.secret}")
private String someSecret;
#Value("${some.username}")
private String someUsername;
#Value("${some.password}")
private String somePassword;
public AuthInfo getPrevAuth() {
return prevAuth;
}
public void setPrevAuth(AuthInfo prevAuth) {
this.prevAuth = prevAuth;
}
private AuthInfo prevAuth;
public AuthInfo getAuthInfo() throws IOException {
if (this.prevAuth != null && this.prevAuth.isNotExpired()) {
return this.prevAuth;
}
return this.Authenticate();
}
private AuthInfo Authenticate() throws IOException {
final String url = this.someUrl + "/api/oauth/v1/token";
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
String clientIdSecret = this.someClientId +":"+ this.someSecret;
String authString = Base64.getEncoder().encodeToString(clientIdSecret.getBytes());
headers.add("Authorization", "Basic " + authString);
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("username", this.someUsername);
map.add("password", this.somePassword);
map.add("grant_type", "password");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
ResponseEntity<?> response = restTemplate.postForEntity(url, request, String.class);
String bodyString = response.getBody().toString();
ObjectMapper mapper = new ObjectMapper();
try {
AuthInfo authInfo = mapper.readValue(bodyString, AuthInfo.class);
this.prevAuth = authInfo;
return this.prevAuth;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
And now how do I need to create service which checks if that access token valid if it hasn't expired and how to use refresh token. When access token expires I could ask new token with refresh token? Would be good to get any examples.
First of all, As I see in your code, you are using password grant type, not client credentials, and because of this, you pass also user credentials (username and password) in addition to the client credentials, client id and client secret.
Anyway, the reason because all the examples you found to check expiration are using jwt tokens is because these tokens have this information coded in the token itself, so you can parse it using some kind of library like Nimbus Jose and get the "exp" claim and check directly if that date is before or after the actual date.
If the token is an opaque one (not jwt). You don't have any way to check the expiration without call the server who issued that token. Normally the server (an oauth2 server) provides and endpoint called introspect in which you pass a token and it responds indicating if this token is valid or is not, because it has expired or it is revoked etc..

OAuth2.0 authentication of Dynamics CRM WebAPIs from a background Java (Spring) application

I need to authenticate against OAuth2.0 Microsoft Dynamics CRM from a background Java application; background because it's an integration app between the ERP of the customer and its Dynamics online instance.
I tried to use spring-security-oauth2 classes to get an high level set of resource to handle authentication, but i can't retrieve the initial token, while I'm successful if I try with building "manually" the http requests needed.
I wrote a simple Java application to test the authentication and I had this piece of code working, with content that is the String representation of the access token JSon:
String accessTokenURL = "https://login.microsoftonline.com/common/oauth2/token";
CloseableHttpClient client = HttpClients.createDefault();
HttpPost requestToken = new HttpPost(accessTokenURL);
requestToken.addHeader("Cache-Control", "no-cache");
requestToken.addHeader("Content-Type", "application/x-www-form-urlencoded");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("grant_type", "password"));
params.add(new BasicNameValuePair("client_id", clientId));
params.add(new BasicNameValuePair("resource", resource));
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("client_secret", clientSecret));
requestToken.setEntity(new UrlEncodedFormEntity(params));
CloseableHttpResponse response = client.execute(requestToken);
InputStream is = response.getEntity().getContent();
String content = IOUtils.toString(is);
System.out.println(content);
client.close();
resource is the Dynamics online instance of the customer.
I tried something similar using Spring Security OAuth2 client classes but I always get "401 Unauthorized":
ResourceOwnerPasswordResourceDetails resourceObj = new ResourceOwnerPasswordResourceDetails();
resourceObj.setClientId(clientId);
resourceObj.setClientSecret(clientSecret);
resourceObj.setGrantType("password");
resourceObj.setAccessTokenUri(accessTokenURLWithResource);
// resourceObj.setId(resource);
resourceObj.setTokenName("bearer_token");
resourceObj.setUsername(username);
resourceObj.setPassword(password);
AccessTokenRequest atr = new DefaultAccessTokenRequest();
Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
headersMap.put("Cache-Control", Arrays.asList("no-cache"));
headersMap.put("Content-Type", Arrays.asList("application/x-www-form-urlencoded"));
atr.add("client_id", clientId);
atr.add("resource", resource);
atr.add("client_secret", clientSecret);
atr.add("username", username);
atr.add("password", password);
OAuth2ClientContext context = new DefaultOAuth2ClientContext(atr);
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceObj, context);
OAuth2AccessToken token = restTemplate.getAccessToken();
System.out.println(new Gson().toJson(token));
I tried using different ways to pass the access token URL and resource but the result is always the same.
Any help or any other advice about other high level library to be used in this case are appreciated, thanks.
Thanks to some hints of #fateddy I came to a solution. This piece of code works, now I'll try to integrate in my application
ResourceOwnerPasswordResourceDetails resourceObj = new ResourceOwnerPasswordResourceDetails();
// resourceObj.setClientId(clientId);
// resourceObj.setClientSecret(clientSecret);
resourceObj.setGrantType("password");
resourceObj.setAccessTokenUri(accessTokenURLWithResource);
// resourceObj.setId(resource);
resourceObj.setTokenName("bearer_token");
// resourceObj.setUsername(username);
// resourceObj.setPassword(password);
AccessTokenRequest atr = new DefaultAccessTokenRequest();
Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
headersMap.put("Cache-Control", Arrays.asList("no-cache"));
headersMap.put("Content-Type", Arrays.asList("application/x-www-form-urlencoded"));
atr.add("client_id", clientId);
atr.add("resource", resource);
atr.add("client_secret", clientSecret);
atr.add("username", username);
atr.add("password", password);
OAuth2ClientContext context = new DefaultOAuth2ClientContext(atr);
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceObj, context);
OAuth2AccessToken token = restTemplate.getAccessToken();
System.out.println(new Gson().toJson(token));

Error Response while getting jwt access token for google user with Google Credential Object

I am trying to get the jwt access tokens for each user of my gsuite domain using the GoogleCredential and JacksonFactory libraries.
Code sample -
GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(clientEmail)
.setServiceAccountScopes(scopes)
.setServiceAccountPrivateKeyFromP12File(privateKeyFile)
.setServiceAccountUser(userEmail)
.build();
credential.refreshToken();
String accessToken = credential.getAccessToken();
All fields - clientEmail, scopes, key and userEmail are neither null nor empty
For a few number of users I am not able to get the access token and am getting this error
com.google.api.client.repackaged.com.google.common.base.Preconditions.checkNotNull(Preconditions.java:191) com.google.api.client.util.Preconditions.checkNotNull(Preconditions.java:127) com.google.api.client.json.jackson2.JacksonFactory.createJsonParser(JacksonFactory.java:96) com.google.api.client.json.JsonObjectParser.parseAndClose(JsonObjectParser.java:85) com.google.api.client.json.JsonObjectParser.parseAndClose(JsonObjectParser.java:81) com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:88) com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287) com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307) com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:269) com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489) com.hubble.hubbleEngine.policyTypes.OAuth.getJWTAccessToken(OAuth.java:815)
This is happening only the first time, I am trying to get the access tokens. When I try to get the access tokens again for all users, I am able to get the access tokens for the users which were throwing the error the first time.
I debugged a bit and saw that the error gets generated from the following function present in com.google.api.client.auth.oauth2.TokenRequest
public final HttpResponse executeUnparsed() throws IOException {
// must set clientAuthentication as last execute interceptor in case it needs to sign request
HttpRequestFactory requestFactory =
transport.createRequestFactory(new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
if (requestInitializer != null) {
requestInitializer.initialize(request);
}
final HttpExecuteInterceptor interceptor = request.getInterceptor();
request.setInterceptor(new HttpExecuteInterceptor() {
public void intercept(HttpRequest request) throws IOException {
if (interceptor != null) {
interceptor.intercept(request);
}
if (clientAuthentication != null) {
clientAuthentication.intercept(request);
}
}
});
}
});
// make request
HttpRequest request =
requestFactory.buildPostRequest(tokenServerUrl, new UrlEncodedContent(this));
request.setParser(new JsonObjectParser(jsonFactory));
request.setThrowExceptionOnExecuteError(false);
HttpResponse response = request.execute();
if (response.isSuccessStatusCode()) {
return response;
}
throw TokenResponseException.from(jsonFactory, response);
}
The request.execute() hits the "https://accounts.google.com/o/oauth2/token" to get the token but it is throwing some error response. Due to this it throws the TokenResponseException mentioned at last. Here, the response.getContent() is null due to which the whole null exception is occuring.
Is there a way to know, which kind of error response is thrown by the call. (>300 or <200)? Or why such a case is happening ?

sheets api error access denied exception desp Requested client not authorized

Hi I am using Google apis.. I have successfully able to access google drive and google calendar but when i try to access google spreadsheet i am getting following exception.
Exception in thread "main" com.google.gdata.util.AuthenticationException: Failed to refresh access token: 403 Forbidden
{
"error" : "access_denied",
"error_description" : "Requested client not authorized."
}
Caused by: com.google.api.client.auth.oauth2.TokenResponseException: 403 Forbidden
{
"error" : "access_denied",
"error_description" : "Requested client not authorized."
}
My code is as follows
private static Credential authorize() throws Exception {
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
String SERVICE_ACCOUNT_EMAIL = "xxx#developer.gserviceaccount.com";
List<String> SCOPES = Arrays.asList("https://spreadsheets.google.com/feeds/");
GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(jsonFactory).setServiceAccountId(SERVICE_ACCOUNT_EMAIL).setServiceAccountScopes(SCOPES)
.setServiceAccountPrivateKeyFromP12File(
new java.io.File("xxx.p12"))
.setServiceAccountUser("xx#zzz.com")
.build();
return credential;
}
public static void main(String[] args) throws Exception {
Credential credential = authorize();
SpreadsheetService service = new SpreadsheetService("new data service ");
service.setProtocolVersion(SpreadsheetService.Versions.V3);
service.setOAuth2Credentials(credential);
// Define the URL to request. This should never change.
URL SPREADSHEET_FEED_URL = new URL(
"https://spreadsheets.google.com/feeds/spreadsheets/private/full");
// Make a request to the API and get all spreadsheets.
SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
// Iterate through all of the spreadsheets returned
for (SpreadsheetEntry spreadsheet : spreadsheets) {
// Print the title of this spreadsheet to the screen
System.out.println(spreadsheet.getTitle().getPlainText());
}
}
Thanks
I was only passing the spreadsheet scope, I have to pass both drive and sheet scope. Now I am able to read spreadsheets from drive.. Here is the corrected code.
String SERVICE_ACCOUNT_EMAIL = "xxxx#developer.gserviceaccount.com";
ArrayList<String> scopes = new ArrayList<String>();
scopes.add(0, DriveScopes.DRIVE);
scopes.add(1, "https://spreadsheets.google.com/feeds");
GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(jsonFactory).setServiceAccountId(SERVICE_ACCOUNT_EMAIL).setServiceAccountScopes(scopes)
.setServiceAccountPrivateKeyFromP12File(
new java.io.File("xx.p12"))
.setServiceAccountUser("yyy#example.com")
.build();

Resources