Getting Bearer token in OAuth2.0 using Rest Assured - oauth-2.0

For my API testing, I have been getting the Authentication Token with the help of Postman. API uses OAuth2.0 for authentication.
While using Postman, I am entering the details like Token Name, Grant Type, Access Token Url, Client ID, Client Secret, Scope, Client Authentication. Once clicked on the Request Token, Bearer token is received and is updated in the Header of the request. Please refer the image attached.Getting OAuth2.0 bearer token with Postman
But now, I want to do it with Rest Assured using Java. Hence I want to know the code how do I get the Bearer token by using Rest Assured?

Assuming you are sending the client id secret and other details in the Query Parameters, for the GET and your response header access_token has the value you are looking.
public class Sample {
String oauth_token ;
#BeforeTest
public void sampletest() {
oauth_token = RestAssured.given().auth().basic("username", "password").
.queryParams("client_id", "client_id_value")
.queryParams("client_secret", "client_secret_value")
.queryParams("grant_type", "authorization_code")
.queryParams("redirect_uri", "https://someuritoredirect")
.queryParams("otherparams", "sampleparam")
.when().get("https://uri.to.get.hostname.com/oauth2/access_token")
.then()
.statusCode(200)
.extract().header("access_token");
}
}

Related

Request had invalid authentication credentials. Expected OAuth 2 access token error

I need to read and import google people contacts but I get the following error:
"Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project."
"status": "UNAUTHENTICATED"
This is the script (classic asp) I am using:
StrURL="https://people.googleapis.com/v1/people/get"
ApiKey="my api key"
Set objXMLHTTP = CreateObject("Msxml2.ServerXMLHTTP.6.0")
objXMLHTTP.Open "GET", StrURL, False
On Error Resume Next
objXMLHTTP.setRequestHeader "Authorization", "Bearer " & ApiKey
If Err.Number<>0 Then Response.Write "Error:" & Err.Description & "<br>"
On Error GoTo 0
objXMLHTTP.send
content = CStr(objXMLHTTP.ResponseText)
statuscode = objXMLHTTP.Status
How can I get the token using classic asp? Can anyone help me?
objXMLHTTP.setRequestHeader "Authorization", "Bearer " & ApiKey
You appear to be sending an api key. An api key is not a bearer token. Api keys only grant you access to public data, not private user data.
In order to access private user data you need to request authorization from that user to access that data that is done using Oauth2
Once you have been grated consent of the user to access their data you will have an access token. This access token can then be sent to the api in the authorization header.
I haven't used asp classic in years. These videos may help you understand how to make the authorization request.
Google 3 Legged OAuth2 Flow
How to create web app credetinals
Understanding oauth2 with curl

Feign Oauth how to manually set the bearer token value?

I'm developping a Rest API, MyApi.
In there, I'm using Feign (and swagger codegen) to generate a client for another API, let's call it Ext-API.
The user will have called Ext-API previously and among other things will have retrieved a JWT Token.
He'll then call my API using Basic Auth and in the body it'll give me the JWT token.
I'm to use this JWT token as auth header to connect to Ext-API from my API and do some more stuff on behalf of the user.
However all example of Oauth & Feign example rely on the Oauth also being used to connect to the API using the generated client.
I can't find how I could, on every request, update the Oauth Token.
There are nothing exposed by feign to do this.
Atm I'm using regular Rest template.
You can used #RequestHeader in feign Client, see below
#FeignClient(name = "<name>", configuration = <configclass>)
public interface Client {
public final String AUTH_TOKEN = "Authorization";
#RequestMapping(method = RequestMethod.GET, value = "users", produces = "application/json")
public HttpEntity<List<User>> getUsers(#RequestHeader(AUTH_TOKEN) String oruToken,
#RequestParam("<param>") Integer value);
}
and from you program you can pass token to feign client

Auth0 JWT Access Tokens

I am having difficulty getting Auth0 to return access tokens in JWT format. I need them in JWT format in order that I can verify them using a Java JWT library.
I am using Auth0 lock to login, and use /oauth/token to get the access token - I have tried setting the audience to our API identifier (in multiple places including the lock auth params, and the /oauth/token payload), without success - the access token is returned however not a JWT.
Alternatively, is there a Java library for validating "native" Auth0 access tokens?
var options = {
auth: {
redirectUrl: '<redirect_link>',
responseType: 'code',
params: {
audience: '<API_identifier>',
scope: 'openid offline_access'
}
},
allowedConnections: ['Username-Password-Authentication']
};
var lock = new Auth0Lock('<clientId>', '<auth0_Host>', options);
lock.show();
The returned code is used to POST to https://<host>/oauth/token with data:
client_id=<client_id>&redirect_uri=<redirect_url>&client_secret=<client_secret>&code=<returned_code>&grant_type=authorization_code&audience=<API_identifier>
Which is successful but the access token is not JWT, for example: "access_token":"sG99DAJI789SYgTj"
Using the scope openid returns an id_token in JWT format, but from reading the documentation this token should not be used for API authorisation.
It seems Auth0 is using OpenID connect, that is an extension of OAuth2. After a successful end-user authentication, the server returns an ID Token in JWT format and an access token
ID Token
The ID Token is a security token that contains Claims about the Authentication of an End-User by an Authorization Server when using a Client, and potentially other requested Claims. The ID Token is represented as a JSON Web Token (JWT) [JWT].
You can validate the ID Token at client side using any JWT library, but the validation rules for access tokens are different
3.2.2.9. Access Token Validation
To validate an Access Token issued from the Authorization Endpoint with an ID Token, the Client SHOULD do the following:
Hash the octets of the ASCII representation of the access_token with the hash algorithm specified in JWA for the alg Header Parameter of the ID Token's JOSE Header. For instance, if the alg is RS256, the hash algorithm used is SHA-256.
Take the left-most half of the hash and base64url encode it.
The value of at_hash in the ID Token MUST match the value produced in the previous step.
So, basically to validate it you need to compute the digest of the access_token using the hash algorithm of ID token, and check that it matches with the at_hash claim of ID Token

How to call JHipster (Spring) OAuth2 Rest server using Postman Authentication helpers

Postman has Authentication helpers to help with authenticated calls and I'm trying to use the OAuth 2.0 helper to call a REST server created by JHipster using Spring (Security, Social, etc).
I've tried a lot of configurations, this is the screen (client ID and Secret were masked):
For the Authorization URL I've tried:
http://127.0.0.1:8080/oauth/authorize
http://127.0.0.1:8080/#/login (the app's login route)
The closer I get from receiving a token back to Postman is:
I don't know why it's erring like this. Maybe I'm setting the Callback URL incorrectly? Do I need to do this in the server or in the client (AngularJS)?
Does anyone have any idea of what's wrong? I appreciate your help.
JHipster is currently setup to use the "password" oauth2 grant type. The helper oauth2 helper only seems to work with "authorization code" and "client credentials" grant types.
What you'll want to do is first call your app's token endpoint directly as the angular app does in
src/main/webapp/scripts/components/auth/provider/auth.oauth2.service.js
POST http://localhost:8080/oauth/token?username=MY_USERNAME&password=MY_PASSWORD&grant_type=password&scope=read%20write
where your username and password can be "user" and "user" respectively, for example and with one header set:
Authorization: Basic AAAAAA
where AAAAAA is your (clientId + ":" + clientSecret)--all base64-encoded. You can use https://www.base64encode.org/. For example if your clientId is "jhipsterapp" and your clientSecret is "mySecretOAuthSecret", replace AAAAAA with "amhpcHN0ZXJhcHA6bXlTZWNyZXRPQXV0aFNlY3JldA==" since that is "jhipsterapp:mySecretOAuthSecret" base64-encoded.
That should return you an access_token. Now hit your API endpoints by calling them with the access_token from your password request in your header like this.
Authorization: Bearer access_token_from_earlier_token_request
Update: if you're using microservices and UAA, then see Niel's answer https://stackoverflow.com/a/45549789/1098564
To build on #sdoxsee's answer:
Currently (August 2017) JHipster generates a class called UaaConfiguration with the configure(ClientDetailsServiceConfigurer) method setting up the client ID, client secret, scope and grant type. Refer to these settings (including the referenced JHipster properties in the application*.yml) to populate the Postman authentication helper, using /oauth/token as both Auth URL and Access Token URL.
Example:
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
/*
For a better client design, this should be done by a ClientDetailsService (similar to UserDetailsService).
*/
clients.inMemory()
.withClient("web_app")
.scopes("openid")
.autoApprove(true)
.authorizedGrantTypes("implicit", "refresh_token", "password", "authorization_code")
.and()
.withClient(jHipsterProperties.getSecurity().getClientAuthorization().getClientId())
.secret(jHipsterProperties.getSecurity().getClientAuthorization().getClientSecret())
.scopes("web-app")
.autoApprove(true)
.authorizedGrantTypes("client_credentials");
}
And,
jhipster:
security:
client-authorization:
client-id: internal
client-secret: internal
Means your authentication helper should be populated as follows:

Request new access token using refresh token in username-password grant in DotNetOpenAuth

I'm trying to implement a OAuth2 Authorization Server using DotNetOpenAuth. The client is JavaScript based thus incapable of holding any secrets. This is exactly the same problem like this question but with another framework.
The client requests (against the token endpoint) access_token and refresh_token with following parameters:
grant_type: password
username: foo
password: bar
This does work. Now I want use the refresh_token and make a request against the token endpoint with the following parameters:
grant_type: refresh_token
refresh_token: ABCDEF
This gives me the following response:
{"error":"invalid_client","error_description":"The client secret was incorrect."}
Which does make (at least some) sense because RFC6749 states that:
Because refresh tokens are typically long-lasting credentials used to
request additional access tokens, the refresh token is bound to the
client to which it was issued. If the client type is confidential or
the client was issued client credentials (or assigned other
authentication requirements), the client MUST authenticate with the
authorization server as described in Section 3.2.1.
If I change my request like so:
grant_type: refresh_token
refresh_token: ABCDEF
client_id: MYCLIENT
client_secret: CLIENT_SECRET
The problem is my client is not supposed to be confidential (because it is client side JavaScript after all).
This is how the client is defined:
New ClientDescription(ApiKey, New Uri(allowedCallback), ClientType.Public)
I searched through the DotNetOpenAuth source code and found no use of the ClientType. To me it looks like it is not used at all.
It is also not possible to the set an empty client secret, because the DotNetOpenAuth source code actively checkes against this (ClientAuthenticationModules.cs):
if (!string.IsNullOrEmpty(clientSecret)) {
if (client.IsValidClientSecret(clientSecret)) {
return ClientAuthenticationResult.ClientAuthenticated;
} else { // invalid client secret
return ClientAuthenticationResult.ClientAuthenticationRejected;
}
} else { // no client secret provided
return ClientAuthenticationResult.ClientIdNotAuthenticated;
}
If I take a look at MessageValidationBindingElement.cs:
if (authenticatedClientRequest != null) {
string clientIdentifier;
var result = this.clientAuthenticationModule.TryAuthenticateClient(this.AuthServerChannel.AuthorizationServer, authenticatedClientRequest, out clientIdentifier);
switch (result) {
case ClientAuthenticationResult.ClientAuthenticated:
break;
case ClientAuthenticationResult.NoAuthenticationRecognized:
case ClientAuthenticationResult.ClientIdNotAuthenticated:
// The only grant type that allows no client credentials is the resource owner credentials grant.
AuthServerUtilities.TokenEndpointVerify(resourceOwnerPasswordCarrier != null, accessTokenRequest, Protocol.AccessTokenRequestErrorCodes.InvalidClient, this.clientAuthenticationModule, AuthServerStrings.ClientSecretMismatch);
break;
default:
AuthServerUtilities.TokenEndpointVerify(false, accessTokenRequest, Protocol.AccessTokenRequestErrorCodes.InvalidClient, this.clientAuthenticationModule, AuthServerStrings.ClientSecretMismatch);
break;
}
Espacially the comment The only grant type that allows no client credentials is the resource owner credentials grant. makes me wonder. Does that mean that in my scenario the JS client should send username/password along? Nope this will raise the following exception:
AccessTokenResourceOwnerPasswordCredentialsRequest parameter 'grant_type' to have value 'password' but had 'refresh_token' instead.
Which is okay to me, because I don't want the client to keep the password.
So here my questions:
Did I unterstand something fundamentally wrong about the password-grant, refresh_token scheme?
As I see it in a JS client the client_id is public knowledge, so it does not serve any security purpose. Am I correct?
Does it makes sense to change DotNetOpenAuth to make use of the ClientType.Public?
Would it make any difference if I just use client_id and client_secret as not secret? E.g. just supply dummy values? What are the security implications?

Resources