I've used the below code:
OAuthClient client = new OAuthClient(new URLConnectionClient());
OAuthClientRequest request =
OAuthClientRequest.tokenLocation("url")
.setGrantType(GrantType.IMPLICIT)
.setClientId("clientid")
.setRedirectURI("redirecturl")
.setScope("scope")
.buildQueryMessage();
request.addHeader("Accept", "application/json");
request.addHeader("Content-Type", "application/json");
System.out.println(request);
String token = client.accessToken(request, OAuth.HttpMethod.POST, OAuthJSONAccessTokenResponse.class).getAccessToken();
Below error is occurred when run the code:
Exception in thread "main" OAuthProblemException{error='unsupported_response_type', description='Invalid response! Response body is not application/json encoded', uri='null', state='null', scope='null', redirectUri='null', responseStatus=0, parameters={}}
at org.apache.oltu.oauth2.common.exception.OAuthProblemException.error(OAuthProblemException.java:63)
at org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse.setBody(OAuthJSONAccessTokenResponse.java:76)
at org.apache.oltu.oauth2.client.response.OAuthClientResponse.init(OAuthClientResponse.java:92)
at org.apache.oltu.oauth2.client.response.OAuthAccessTokenResponse.init(OAuthAccessTokenResponse.java:65)
at org.apache.oltu.oauth2.client.response.OAuthClientResponse.init(OAuthClientResponse.java:101)
at org.apache.oltu.oauth2.client.response.OAuthAccessTokenResponse.init(OAuthAccessTokenResponse.java:60)
at org.apache.oltu.oauth2.client.response.OAuthClientResponse.init(OAuthClientResponse.java:120)
at org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory.createCustomResponse(OAuthClientResponseFactory.java:82)
at org.apache.oltu.oauth2.client.URLConnectionClient.execute(URLConnectionClient.java:111)
at org.apache.oltu.oauth2.client.OAuthClient.accessToken(OAuthClient.java:65)
at TestCLass.main(TestCLass.java:57)
Process finished with exit code 1
Related
My project is a web api project which is using owin for generating token after authentication. it is built using asp.net framework.
It currently accepts token request in below format -
var client = new RestClient("http://localhost:63202/1.0/token");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "client_credentials");
request.AddParameter("client_id", "12345667");
request.AddParameter("client_secret", "secret");
I want my API to support Json raw body instead of URL encoded one with the token request as below -
var client = new RestClient("http://localhost:63202/1.0/token");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
var body = #"{" + "\n" +
#" "grant_type": "client_credentials"," + "\n" +#" "client_id": "1234567890""," + "\n" +#"client_secret": "channelsintegration123456789012345" + "\n" +
#"}"
request.AddParameter("application/json", body, ParameterType.RequestBody);
Issue - When the request is made and ValidateClientAuthentication() method is hit, the context doesn't have client id and client secret when I make the above (#2) request.
Hello team I have a Application on https://console.cloud.google.com of type Desktop
once after signin with the test user credentials , i have returned successfully and then trying to get the token using the
final String tokenUrl = "https://oauth2.googleapis.com/token";
// The original redirect URL
final URI redirectUri = new URI(this.redirectUri);
// Using HttpClient to make the POST to exchange the auth code for the token
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(tokenUrl);
// Adding the POST params to the request
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("code", code));
urlParameters.add(new BasicNameValuePair("client_id", googleClientId));
urlParameters.add(new BasicNameValuePair("client_secret", googleClientsecret));
urlParameters.add(new BasicNameValuePair("redirect_uri", redirectUri.toString()));
urlParameters.add(new BasicNameValuePair("scope", scope));
urlParameters.add(new BasicNameValuePair("grant_type", grantType));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
// Execute the request
System.out.println(post.toString());
HttpResponse response = client.execute(post);
// Print the status code
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
// Get the content as a String
String content = EntityUtils.toString(response.getEntity());
System.out.println("Result : " + content.toString());
am getting the error as below
Response Code : 400
Result : {
"error": "invalid_request",
"error_description": "client_secret is missing."
}
i know am not using google API's to get the token , but the api here am using also should work right?
please please help me here
I am using oauth2/token to authenticate my application and get the access_token. Bellow is the java code which is working fine.
private String getToken() throws Exception {
String access_token = "";
String url = "https://login.windows.net/MyApplication_ID_here/oauth2/token";
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("grant_type", "client_credentials"));
urlParameters.add(new BasicNameValuePair("client_id", "MyApplication_ID_here"));
urlParameters.add(new BasicNameValuePair("client_secret", "MyApplication_secret_here"));
urlParameters.add(new BasicNameValuePair("resource", "https://graph.microsoft.com"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("Sending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
String responseAsString = EntityUtils.toString(response.getEntity());
System.out.println(responseAsString);
try {
access_token = responseAsString.split(",")[6].split("\"")[3]; // get the access_token from response
} catch (Exception e) {
e.printStackTrace();
return null;
}
return access_token;
}
Response :
{"token_type":"Bearer","expires_in":"3599","ext_expires_in":"0","expires_on":"1493011626","not_before":"1493007726","resource":"https://graph.microsoft.com","access_token":"eyJ0e..."}
then I am using access_token to load the memberOf value which is not working and gives me the Access Token missing or malformed error. Bellow is the java code
private void getMemberOf()
{
HttpClient httpclient = HttpClients.createDefault();
try
{
URIBuilder builder = new URIBuilder("https://graph.windows.net/MyApplication_ID_here/users/test#testABC.onmicrosoft.com/memberOf?api-version=1.6");
URI uri = builder.build();
HttpGet request = new HttpGet(uri);
request.addHeader("Authorization", "Bearer " + access_token);
request.addHeader("Content-Type", "application/json");
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
}
catch (Exception e)
{
e.getMessage();
}
}
Response :
Response Code : 401
{"odata.error":{"code":"Authentication_MissingOrMalformed","message":{"lang":"en","value":"Access Token missing or malformed."},"date":"2017-04-24T04:39:38","requestId":"c5aa2abe-9b37-4611-8db1-107e3ec08c14","values":null}}
Can someone please tell me which part of the above request is wrong? Am I not setting access_token correctly?
According to your code , your access token is for resource "https://graph.microsoft.com"(Microsoft Graph API) ,But the access token is used for "https://graph.windows.net"(AAD Graph API) :
URIBuilder builder = new URIBuilder("https://graph.windows.net/MyApplication_ID_here/users/test#testABC.onmicrosoft.com/memberOf?api-version=1.6");
If you want to call Azure AD graph api , you need to get access token for Azure AD Graph API .
I got this issue while performing the CRUD operation on Azure AD B2C service via AD Graph API for user management.
The idea is to get the access token for the resource "graph.windows.net" instead I was using my tenant App Id URI as it was suggested here.
*might help people who faced the same issue and landed up here
When I try to execute OAuth v1 request I got
"Response{code=401, message='Unauthorized', body='null', headers={Keep-Alive=timeout=60, Transfer-Encoding=chunked, null=HTTP/1.1 401 Unauthorized, Server=CodeBig, WWW-Authenticate=OAuth realm="classified.net", Connection=keep-alive, CodeBig-Error-Message=missing authentication credentials, Date=Sun, 16 Oct 2016 08:16:16 GMT, Via=1.1 CodeBig, Content-Type=text/plain}}"###
Here is a code snippet of using scribejava
String apiKey = "fsfsfsf";
String apiSecret = "fsfsfsfsf";
String PROTECTED_RESOURCE_URL = "https://somerealm.net/";
OAuth10aService service = new ServiceBuilder().apiKey(apiKey).apiSecret(apiSecret).signatureType(SignatureType.QueryString).build(new MyAOuthv1());
OAuthRequest request = new OAuthRequest(Verb.POST, PROTECTED_RESOURCE_URL, service);
request.addOAuthParameter(OAuthConstants.TIMESTAMP, service.getApi().getTimestampService().getTimestampInSeconds());
request.addOAuthParameter(OAuthConstants.NONCE, service.getApi().getTimestampService().getNonce());
request.addOAuthParameter(OAuthConstants.CONSUMER_KEY, "blahblahblah");
request.addOAuthParameter(OAuthConstants.CONSUMER_SECRET, "blahblahblah");
request.addOAuthParameter(OAuthConstants.SIGN_METHOD, service.getApi().getSignatureService().getSignatureMethod());
request.addOAuthParameter(OAuthConstants.VERSION, "1.0");
request.addOAuthParameter(OAuthConstants.SIGNATURE, getSignature(service, request));
request.addPayload("{\"id\":12345,\"message\":\"some text\"}");
request.addHeader("Content-Type", "application/json");
Response response = request.send();
However If I use firefox's REST Client I get it working.
What is wrong? OAuth vesrion is 1.0
Why don't you use OAuth10aService::signRequest method?
I always get Bad Request 400 from IdentityServer3. I am trying for 3 days now but no luck :( Anyone could please tell me what am I doing wrong?
I am trying to access IdentityServer3 hosted by another vendor that I have no control. The vendor has asked us to implement Implement OAuth2 authentication with Bearer token. The vendor provided us with the Client ID, Client Secret and the URL to be used is http://www.xxxxxx.com/identity/connect/token
The vendor told us to use to request bearer token and use it in the request headers Authorization: Bearer
I can successfully obtain the bearer token from vendor. But when I call the
GET /api/profiles/myemailaddress#gmail.com I get Bad Request 400
Here is what I have done:
TokenClient client = new TokenClient("http://www.xxxxxx.com/identity/connect/token", "myclientid", "myclientsecret", AuthenticationStyle.PostValues);
var response = await client.RequestResourceOwnerPasswordAsync("myemailaddress#gmail.com", "mypassword", "profile"); // successfully gives me the token
i got the access token, now i want to use the token to request user profile:
var clienthttp = new HttpClient();
clienthttp.BaseAddress = new Uri("http://www.xxxxxx.com");
clienthttp.SetBearerToken(response.AccessToken);
var json = await clienthttp.GetStringAsync("http://www.xxxxxx.com/api/profiles/myemailaddress#gmail.com"); // error Bad Request 400
Additional Info:
"scopes_supported":["profile","offline_access"],
"claims_supported":[]
Thank you.
The vendor was expecting additional value in the header. Since my request was missing that additional value, they returned Bad Request. I had to modify my code to find the exact reason of bad request.
Here is the updated code, might be useful for someone:
var client = new HttpClient();
client.BaseAddress = new Uri("http://www.xxxxx.com");
client.SetBearerToken(response.AccessToken);
var callApiResponse = client.GetAsync("api/profiles/myemailaddress#gmail.com").Result;
string tokenresponse = callApiResponse.StatusCode.ToString();
string clientresult = callApiResponse.Content.ReadAsStringAsync().Result;
tokenresponse: "Bad Request 400"
clientresult: "Missing CompanyID in the header"
Then I knew that they also expect companyid in the header so I added it. then all was good.
client.DefaultRequestHeaders.Add("CompID", "xxxxxx");
I had a similar error (Response status code does not indicate success: 400 (Bad Request)) for different resource not identity server. i manage to resolve that using FormUrlEncodedContent
Refer below code
using (HttpClient client = new HttpClient())
{
string baseUrl = "https://*******.com/****"
Dictionary<string, string> jsonValues = new Dictionary<string, string>();
jsonValues.Add("username", "******");
jsonValues.Add("password", "******");
var contenta = new FormUrlEncodedContent(jsonValues);
var response = await client.PostAsync(baseUrl, contenta);
using (HttpContent content = response.Content)
{
string data = await content.ReadAsStringAsync();
if (data != null)
{
Console.WriteLine(data);
}
}
}