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

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?

Related

Is the authorization code with pkce default on authcode grant type implementation?

We are using oidc-client. The Client setting grant type is authorization code. However, I found out that my authorization code uses PKCE. Because I can use it without client secret and and has code_challenge on the uri. I'm looking onto it on how it was set but I couldn't find it.
I just want to know if the AuthCode with PKCE is the default one now. Correct me if I'm wrong, when you don't set in your oidc-client that you will use the PKCE then you should use the normal auth code that requires the client secret?
This is my client:
getClientSettings(): UserManagerSettings {
const config = this.config._envConfig;
return {
authority: `${config.BaseAuthUrl}`,
client_id: "auth-code-client",
redirect_uri: `${config.BaseRedirectUrl}/signin-callback`,
post_logout_redirect_uri: `${config.BaseRedirectUrl}`,
response_type: "code",
scope:
"scope_1 scope_2 scope_3",
filterProtocolClaims: true,
loadUserInfo: false,
silent_redirect_uri: `${config.BaseRedirectUrl}/renewtoken`,
automaticSilentRenew: true,
revokeAccessTokenOnSignout: true,
monitorSession: true,
};
}
If it indeed is the default behaviour it's very good. There is no downside of using PKCE and you should always use it if possible. PKCE adds another layer of security to the flow, it does not stop you from using client's secret. Also, if the Authorization Server does not support PKCE it should just ignore the parameters, so it doesn't matter for your client if the Authorization Server uses PKCE or not.

Getting Bearer token in OAuth2.0 using Rest Assured

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");
}
}

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:

get an access code from the doorkeeper gem

when we request by click on authorize.........
request send to the
http://localhost:3000/oauth/authorize?client_id=57070f3927deea2d38c50afa042ae0o9u0c539e4d45a79e203cd66d286f9ec8e&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2F&response_type=code
the response come
http://localhost:3000/?code=1560b332321dd2obc99ed3411c78614ce0d59c90e9264c87b7f2f179441d6b4e
now i hve to copy the "code" put in console like below code.....
app_id = "57070f3927deea2d38c50afa042ae0o9u0c539e4d45a79e203cd66d286f9ec8e"
secret = "1dbd541132ca2bdeb9fe83b41d24490b2be445c30fd1856e5914f6d343c4a71b"
client = OAuth2::Client.new(app_id, secret, site: "http://localhost:3000/")
client.auth_code.authorize_url(redirect_uri: callback)
access = client.auth_code.get_token('1560b332321dd2obc99ed3411c78614ce0d59c90e9264c87b7f2f179441d6b4e', redirect_uri: callback)
access.token
this how the access_token is generated...
is there a better way to get the access code from the dookeeper
This is standard way described by oauth2.0 specification for autorization code based retrieval of access token. There are other ways like implicit, password and client credentials. Check out the details in RFC and try it with Doorkeeper.

Resources