Refresh Token OAuth2 Implementation - oauth-2.0

I have implemented OAuth2 Refresh Token in my project where i have two servers :
- Authentication Server
- Resource Server
Question : Where should i check if my access token has already expired or not ?
Method 1 : Before sending a request to resource server, we check if the access token has been expired or not at the client side only ? If the access token has been expired then we send refresh token to Authentication server to get the new access token and resend the request to resource server with the new access token.
Method 2 : Request goes to resource server and then we get invalid_access in the response & then we sent a request to Authentication server with refresh token to get the new access token & then again send request to resource server with new access token ?
Request you to share your thoughts on the same.
Thanks in advance.

Some good points above - would definitely recommend method 2 - as you've pointed out yourself it is more resilient.
Also the client side code should deal with other possible reasons for 401 responses, such as load balancing flips or changes to token signing keys.
I therefore always write OAuth clients to call APIs like this code snippet, regardless of technology.

Related

Salesforce OAuth User Agent Flow: obtain refresh token with

I am developing a web application that allows any user to connect with its Salesforce account. I've implemented User-Agent Flow and I obtain correctly access_token and other info but I can't obtain refresh_token, even if I have the correct scopes (api, web, refresh_token, offline_access).
This is the request I use:
https://login.salesforce.com/services/oauth2/authorize?response_type=token&scope=refresh_token&client_id=[MY_CLIENT_ID]&redirect_uri=[MY_REDIRECT_URL]
And my redirect URL is:
http://[MYSITE].com/#/services/oauth2/success
(that corresponds to the host from where I make the call)
This call correctly gives me access_token but not refresh_token.
if I use "https" instead "http" as redirect uri I receive this error:
error=invalid_scope&error_description=the requested scope is not available
From the documentation, I read that:
The refresh token for the user-agent flow is only issued if you
requested scope=refresh_token and one of the following scenarios is
true:
....
The redirect URL host matches the request host and includes the servlet services/oauth2/success.
...
I think to be in this case, what am I doing wrong?
Thanks in advance
Try adding Perform requests at any time (refresh_token, offline_access) under Selected OAuth Scopes in your connected app

WSO2 IS: Error using OAuth Authorization Code flow with SOAP API

I'm using the OAuth Authorization Code flow to authenticate the user and authorize my application against the WSO2 Identity Server. I'm using a simple node/express server, with Passport.js, to get the Access Token, and Postman to use that Access Token to make a few test requests to the SOAP APIs.
When using a Bearer Token method to authorize my application, I get the following error in the IS logs: 0 active authenticators registered in the system. The system should have at least 1 active authenticator service registered. I get the following error in Postman: 500 Internal Server Error, with the following response body, <faultstring>Authentication failure</faultstring>.
Here is what it looks like in Postman:
The same Access Token works with a REST API request, like "https://localhost:9443/scim2/Me".
Can anyone tell me what I'm missing here?
SOAP APIs in WSO2 Identity Server cannot be authenticated with Bearer tokens. They can be authenticated with Basic authentication and cookies. That's the reason for getting Authentication failure in the response.
But REST APIs in the Identity Server can be authenticated with Bearer tokens. So /scim2/Me authenticate successfully with access token.
Try to get the Access token manually from Authorize service and use it
Step 1: Get authorization code
https://<is_server_url>:9443/oauth2/authorize?client_id=<id>&redirect_uri=<callback_url>&response_type=code&scope=openid
You will get an authorization code on the callback URL
Step 2: Call token service to get access token
Post https://<is_server_url>:9443/oauth2/token
Content-Type:application/x-www-form-urlencoded
Authorization:Basic <base64encoded "<client_id>:<client_secret>">
grant_type:authorization_code
scope:openid
code:<code_from_step_1>
redirect_uri:<callback_url>
exp:
client_id=**abcdefgh12345678**
client_secret=**xyzsecretkey**
callback_url=**http://locahost/callback**
scope=openid
server: localhost
base64encode(client_id:client_secret)= base64encode(abcdefgh12345678:xyzsecretkey) => YWJjZGVmZ2gxMjM0NTY3ODp4eXpzZWNyZXRrZXk=
GET https://localhost:9443/oauth2/authorize?client_id=**abcdefgh12345678**&redirect_uri=**http://locahost/callback**&response_type=code&scope=openid
it will make a request back to the callback url with a parameter code, lets say code=this01is02your03code, please check your browser address bar
POST https://localhost:9443/oauth2/token
HEADERS
Content-Type:application/x-www-form-urlencoded
Authorization:Basic **YWJjZGVmZ2gxMjM0NTY3ODp4eXpzZWNyZXRrZXk=**
BODY
grant_type:authorization_code
scope:openid
code:this01is02your03code
redirect_uri:http://locahost/callback
this will return an access token, let say token returned by the server is 12345678ASDFGH
Now you could use this token to call any RestFull or SOAP service
Authorization: Bearer 12345678ASDFGH

How to request access token from Battle.net OAuth with authorization code?

I have a hobby project in mind to use battle.net login. I'm wondering how I can obtain the access token from the API after receiving the authorization code.
This is Oauth flow question rather than a battle.net question.
Currently I can successfully authorize the user for my app which is registered in dev.battle.net and then I try to use the authorization code returned from the battle.net login to obtain the access token by sending a request to https://<region>.battle.net/oauth/token.
However I keep receiving this error:
{
"error": "unauthorized",
"error_description": "An Authentication object was not found in the SecurityContext"
}
I use postman extension to send post requests to that uri. I authenticate my request with my client id and secret. I pass redirect_uri (https://localhost), granty_type (authorization_code), code(the code returned from the previous authorization step). However I keep getting the error above.
I couldn't find much about battle.net online. There are other oauth related help articles but couldn't really find my way.
Wondering if you can help me with this easy stuff. I'm just wondering what I'm skipping here.
Here is the documentation:
https://dev.battle.net/docs/read/oauth
https://localhost is added in my mashery dev account's app settings.
Me again, I resolved this problem after trying almost every combination in the universe:)
Steps to apply:
Don't use the same authorization token for different access token trials, they are not valid
Always use https on every domain you test including localhost, you
redirect_uri must be https as well.
You must use the "basic authentication" in the header of your POST request while requesting the token from the authorization code you obtained from the previous step.
This is one of the most important ones: For requesting token, Pass redirect_uri, client key and secret as POST form parameters to the authenticated request. This is interesting because it's already an authenticated request; why would i need to pass my secret again? Anyways, that's how it works.
Here are the full text:
http://hakanu.net/oauth/2017/01/26/complete-guide-of-battle-net-oauth-api-and-login-button/
This is working prototype:
https://owmatch.me
Thanks.

Web API 2 and HttpClient

I have a web api and MVC project,
The web api is deployed at api.domain.com
The MVC app is deployed at domain.com
I recently secured certain methods on the API, it requires authentication (grant type: password).
I want to have the token passed around in the code behind of the MVC app and not javascript, to keep it secure and away from someone sniffing angular js traffic.
I did some research and I should use the HttpClient class. If this is the case how does this client handle refresh tokens? Right now the token expires after 8 hours, I know a refresh token is also issued but does the HttpClient automatically handle this or do I have to write my own logic to check if a request was denied due to an expired token.
Thank you!
I did some research and I should use the HttpClient class. If this is
the case how does this client handle refresh tokens?
The HttpClient class is, as its name suggest, an HTTP protocol client. It knows strictly nothing about OAuth 2.0 and in this respect nothing about refresh tokens. So you should write this logic yourself. Basically the flow you should follow is something along those lines:
Send an HTTP request t othe target endpoint using the HttpClient and including your existing OAuth Bearer token in the Authorization header field.
If the request succeeds then you are good to go. If the request fails with 401, then you should use your refresh token in order to renew your access token and then repeat step 1 with your new access token.
I think using a HttpMessageHandler can help you.
The way this is wired up to an HttpClient is by using the HttpClient constructor that takes a HttpMessagHandler:
1: // Create client and insert an OAuth message handler in the message path that
2: // inserts an OAuth authentication header in the request
3: HttpClient client = new HttpClient(new OAuthMessageHandler(new HttpClientHandler()));
The HttpClientHandler is the default “network” handler provided by HttpClient that actually sends the request and received the response from the network.
Refer this for complete detail: https://blogs.msdn.microsoft.com/henrikn/2012/02/16/extending-httpclient-with-oauth-to-access-twitter/

OAuth 2.0 for MVC - How does the RequestToken work?

I'm working with OAuth 2.0 for MVC, found here: http://community.codesmithtools.com/CodeSmith_Community/b/tdupont/archive/2011/03/18/oauth-2-0-for-mvc-two-legged-implementation.aspx
For anyone who's worked with this - I'm confused about the RequestToken. There is a controller implemented that lets you get a request token, which expires in 5 minutes, and you pass that token back in to get an AccessToken. But it never checks the request token for validity - it seems like you can pass in any access token you want to. What is the idea for the RequestToken here - are you supposed to create your own method of storing, referencing, and then deleting that token for those 5 minutes?
Thanks,
Andy
This is all about how OAuth works in conjunction with your application Id, application secret key and valid domains for your application. Here is the process in general
Your application sends a request to the OAuth provider using your application Id and secret along with a callback (return Url).
The OAuth provider gets the request, checks your application Id and secret and validates that the callback url is from a domain that you have specified for your application.
2a. If the callback url is not from a domain that you have specified, then the request is rejected with error.
2b If the callback url is from your domain, it returns a temporary request key to your server.
Given that you received a request key, you send that back to the OAuth provider to get the actual access token for the user.
Now, as to why the request key step is in place, this is to prevent and help protect 'bad people' from attempting to use your application id to falsely authenticate other users. By sending the request token to you (a callback URL that you have approved), the OAuth provider has confidence that the request actually came from your servers.
You most certainly could send any string back instead of the request token, but you would quickly get an error back from the OAuth provider as that request token does not correspond to any existing authentication request from any known application.
Lastly, I am not clear on what you mean by 'validating the request token'? You did not generate the token not probably do not have insight into the algorithm to generate the request token. Given that, I am not sure how you would validate this. If you are concerned about validating the first step, take a look at the Facebook OAuth process. In there, they recommend sending a request key as part of your return Url(as a query string parameter). That request key will come back to your application which you could then use as a validation that, indeed, this is a response to a request that you made. How you store and track that request key is up to you (session, database). In the PHP samples, they use a 'state' variable to track a unique/arbitrary string: Facebook OAuth Server Side Login Example (in PHP)

Resources