How to obtain access-token for a RAML API using OAuth 2.0 - oauth-2.0

I was working around with Mule project using RAML and API Manager.
by following procedure given here
AM using API Manager to handle the service tied with characteristics like
Simple Security Manager,
OAuth 2.0 Provider and
OAuth 2.0 Access Token Enforcement.
I have a separate flow for redirection which does following
set 'status' to 302
set 'Location' to URL below
http://localhost:8081/org/oauth/token?grant_type=authorization_code&&client_id=53a406c3e4b0624da8246eed&client_secret=myclientsecret&code=#[message.inboundProperties.code]&redirect_uri=http://localhost:8081/raml-api-with-oauth/redirect
All goes well till here.
But when I try to hit the url for access token I see a message
{"error":"unauthorized_client","error_description":""}
to sumup my question:
please help me with 'OAuth dance' procedure
How do i set a valid contract with the API to facilitate the communication of the clientId and clientSecret necessary for the OAuth dance.
Please help me where am going wrong.
RAML code:
#%RAML 0.8
title: raml-api-with-oauth
version: v1
baseUri: http://localhost:8081/raml-api-with-oauth
securedBy: [oauth_2_0]
securitySchemes:
- oauth_2_0:
description: |
This supports OAuth 2.0 for authenticating all API requests.
type: OAuth 2.0
describedBy:
headers:
Authorization:
description: |
Used to send a valid OAuth 2 access token. Do not use
with the "access_token" query string parameter.
type: string
queryParameters:
access_token:
description: |
Used to send a valid OAuth 2 access token. Do not use together with
the "Authorization" header
type: string
responses:
401:
description: |
Bad or expired token. This can happen if the user or Dropbox
revoked or expired an access token. To fix, you should re-
authenticate the user.
403:
description: |
Bad OAuth request (wrong consumer key, bad nonce, expired
timestamp...). Unfortunately, re-authenticating the user won't help here.
404:
description: Unauthorized
settings:
authorizationUri: org/oauth/authorize
accessTokenUri: org/oauth/token
authorizationGrants: [code,token]
scopes:
- "READ_RESOURCE"
- "POST_RESOURCE"
- basic
- comments
- relationships
- likes
mediaType: application/json
/employee:
get:
description:
This is a Get Call which throws some response in json.
responses:
200:
body:
application/json:
example: |
{
"empcode" : 1,
"ename": "Rafiq",
"company" : "org"
}

Oauth policy is based on Mule Enterprise security, in order to understand the dances for the different types of grants, please see this documentation page:
http://www.mulesoft.org/documentation/display/current/Creating+an+OAuth+2.0a+Web+Service+Provider

The below code represents oauth 2.0 (raml 1.0)
securitySchemes:
oauth_2_0:
description: |
This API supports OAuth 2.0 for authenticating all API requests.
type: OAuth 2.0
describedBy:
headers:
Authorization:
description: |
Used to send a valid OAuth 2 access token. Do not use with the "access_token" query
string parameter.
type: string
queryParameters:
access_token:
description: |
Used to send a valid OAuth 2 access token. Do not use together with the "Authorization"
header
type: string
responses:
401:
description: |
Bad or expired token. This can happen if the user or the API revoked or expired an
access token. To fix, you should re-authenticate the user.
403:
description: |
Bad OAuth request (wrong consumer key, bad nonce, expired timestamp...). Unfortunately,
re-authenticating the user won't help here.
settings:
authorizationUri: INSERT_OAUTH2_AUTHORIZATION_URI
accessTokenUri: INSERT_OAUTH2_ACCESS_TOKEN_URI
authorizationGrants: INSERT_OAUTH2_AUTHORIZATION_GRANTS
scope: [READ,WRITE]
once you include this code in your raml, we need to provide validate
url in oauth policy. https://application-name/validate(external oauth
provider)
or oauth provider should give the url which is required in
raml(authorization and access_token and validation url)
The resources can be enforced with oauth so that it will be more
secured to share the resources.
after generating the flow from raml, we need to deploy the
application to cloudhub.
we need to provide organization client_id and client_secret, so that
it will provide the access_token otherwise it throws wrong client.

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

How to customize token sending while using OAuth2 in OpenApi 3 with password flows?

I am looking for the proper way to specify an Authorization header and not send the word 'bearer' with my token
The custom Authorization header should look like
authorization: 'myToken'
All my attempts to specify the securitySchemes entry with type: OAuth2 seems to produce other results...
The closest I got is something like:
securitySchemes:
Authorization:
type: oauth2
description: This API uses OAuth 2 with the password grant flow.
flows:
password:
tokenUrl: oauth/token
scopes: {}
... but this generates the authorization: 'bearer myToken' header instead of authorization: 'myToken'.
How can such a requirement be specified?

Implicit grant type: Invalid grant_type parameter value WSO2

I try generate a access token in my application on WSO2 using implicit grant type, following the request:
POST /token HTTP/1.1
Host: localhost:8243
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
Postman-Token: d6ef6038-9860-bdc6-3867-70af98b37cc6
grant_type=code&response_type=implicit&client_id=CLIENT_ID&redirect_uri=http%3A%2F%2Flocalhost%3A8888%2Fplayground%2Foauth2client&scope=default
And the request return this error:
{
"error_description": "Invalid grant_type parameter value",
"error": "invalid_request"
}
This is my grant types settings:
Grant Types
Why this error happen, although the settings include the implicit grant type?
I think you are mixing up few things. If you want to use the Implicit grant, you don't use the /token endpoint - you get everything from the authorization endpoint. The request could look like this:
/auth?response_type=token&client_id=...&redirect_uri=...
and after a successful authentication, the client gets an access token right away as part of the redirect URL.
If you have a code and you want to exchange it for an access token and a refresh token, you are using the Authorization code grant. Then the correct grant_type value is authorization_code and you must specify the code in the code URL parameter. So the error message you are getting is correct.
Finally, the token endpoint has no response_type parameter. It's a parameter of the authrization endpoint and the correct value for the implicit flow is token, because you want an access token to be returned.

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

BadRequest when calling ProcessUserAuthorization after requesting "plus.login" scope

I have problems while updating code to new scope. Currently I use userinfo.profile and everything works Ok.
According to Google+ OAuth 2.0 scopes new plus.me scope allows application to know who user is, and plus.login also gives additional access (to age, language, circles, ...).
If I replace userinfo.profile with plus.me - everything works Ok: method WebServerClient.RequestUserAuthorization authorizes user and ProcessUserAuthorization gives me a token.
But if I ask plus.login scope instead - Google adds additional query parameters to my callback and next call to WebServerClient.ProcessUserAuthorization fails , because implementation uses current rul to make new redirect_url, striping "known" parameters and leaving "new unknown" Google parameters. his redirect_url doesn't match on registered in Google Api Console and Google server returns 400 response.
Here is success response from authorization with plus.me scope (from NetOpenAuth.Messaging.Channel log):
Incoming HTTP request: GET http://localhost:40004/Me/LoginComplete?from=Google&state=TWXf6Zq3XYSlwyfCDt3GiQ&code=4/qC_KeuiykcVm1sayIyEdnBjiklxz.AoMfk5TqaXQcsNf4jSVKMpY-GxwThAI
After binding element processing, the received EndUserAuthorizationSuccessAuthCodeResponse (2.0) message is:
code: 4/qC_KeuiykcVm1sayIyEdnBjiklxz.AoMfk5TqaXQcsNf4jSVKMpY-GxwThAI
state: TWXf6Zq3XYSlwyfCDt3GiQ
from: Google
And here is (success) authorization response with plus.login scope:
Incoming HTTP request: GET http://localhost:40004/Me/LoginComplete?from=Google&state=26R-O3YN6u3-5EKIlJzFFw&code=4/zOoeVq8vec068x2-CyPq4PjPNtRT.osemzp8Zl7sQsNf4jSVKMpbcmWQThAI&authuser=0&prompt=consent&session_state=27ca4bd2e70d0721bc1fa781b900a558e59fe4c7..d409
After binding element processing, the received EndUserAuthorizationSuccessAuthCodeResponse (2.0) message is:
code: 4/zOoeVq8vec068x2-CyPq4PjPNtRT.osemzp8Zl7sQsNf4jSVKMpbcmWQThAI
state: 26R-O3YN6u3-5EKIlJzFFw
from: Google
authuser: 0
prompt: consent
session_state: 27ca4bd2e70d0721bc1fa781b900a558e59fe4c7..d409
Call for token (for plus.me scope) will be successful:
Prepared outgoing AccessTokenAuthorizationCodeRequestC (2.0) message for https://accounts.google.com/o/oauth2/token:
code: 4/qC_KeuiykcVm1sayIyEdnBjiklxz.AoMfk5TqaXQcsNf4jSVKMpY-GxwThAI
redirect_uri: http://localhost:40004/Me/LoginComplete?from=Google
grant_type: authorization_code
client_id: 175802076419.apps.googleusercontent.com
client_secret: ********
But with plus.login scope 3 new parameters (authuser, prompt, session_state) are transferred to redirect_url param:
Prepared outgoing AccessTokenAuthorizationCodeRequestC (2.0) message for https://accounts.google.com/o/oauth2/token:
code: 4/zOoeVq8vec068x2-CyPq4PjPNtRT.osemzp8Zl7sQsNf4jSVKMpbcmWQThAI
redirect_uri: http://localhost:40004/Me/LoginComplete?from=Google&authuser=0&prompt=consent&session_state=27ca4bd2e70d0721bc1fa781b900a558e59fe4c7..d409
grant_type: authorization_code
client_id: 175802076419.apps.googleusercontent.com
client_secret: ********
And as soon as this redirect_url does not match registered I receive error:
https://accounts.google.com/o/oauth2/token returned 400 BadRequest: Bad Request
OAuth2 spec says that params code and state are required in authorization response and says noting about adding other parameters. But it also says that
The client MUST ignore unrecognized response parameters
Does this mean that this is DNOA issue and not Google one?
May be DNOA must add nullable responseUri parameter to ProcessUserAuthorization and use it instead of guessing from current url...
What's the easiest workaround (except using Google library)?
Update:
Here is original request for /oauth
Prepared outgoing EndUserAuthorizationRequestC (2.0) message for https://accounts.google.com/o/oauth2/auth:
client_id: 175802076419.apps.googleusercontent.com
redirect_uri: http://localhost:40004/Me/LoginComplete?from=Google
state: TWXf6Zq3XYSlwyfCDt3GiQ
scope: https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/plus.me
response_type: code

Resources