Showing posts with label Oauth. Show all posts
Showing posts with label Oauth. Show all posts

Wednesday, September 20, 2017

Access User Profile API via Google OAuth 2.0 Playground ?

The OAuth Playground is an application/tool by Google for learning how OAuth works. It presents you with a three-step process for selecting the services you want to authorize, generating an access token, and making API requests.
In OAuth terminologies, Google OAuth playground will act as a client Application which does contain client id, Client secret and OAuth Endpoints required to access Service provider.
It also supports custom endpoints as well i.e. using Google OAuth playground you can connect to another service provider as well apart from Google like Salesforce.
Resource Owner: You
Client Application: Google OAuth 2.0 Playground

Service Provider: Google
In this blog, I’ll only focus on Google API and will try to retrieve user profile via playground.





Step 2: You will see a list of scope using which you can access particular resources. As our aim is to fetch user profile so will scroll down and select https://www.googleapis.com/auth/userinfo.profile from Google People API v1 scope.



Step 3:  Click on Authorize APIs button and If you are not logged into google then it will ask for your user credentials and after successful authentication, it will show the authorization consent page. Click on Accept button.


Step 4: Now we have the Authorization Code but if you check Request/Response section then you will notice that playground application hits AUTHORIZATION ENDPOINTS

Authorization request:


We hit this request to the authorization endpoint to obtain an authorization code

https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=https%3A%2F%2Fdevelopers.google.com%2Foauthplayground&prompt=consent&response_type=code&client_id=407408718192.apps.googleusercontent.com&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&access_type=offline

where
response_type  ->  it always should be code, specifies that request is sent to the authorization endpoint to obtain an authorization code. ( Required)
client_id -> The Id issued to this application by Authorization server at the time of registration. (Required)
redirect_uri -> URI registered on the authorization server as a RedirectURI or callback URL. 
Scope -> Access scope of the request

and after successful authentication and authorization, Playground is getting the Authorization Code on its registered redirect URL.

Authorization response:


It contains the Auth code in exchange of which we will get the access token.

/oauthplayground/?code=4%2F0pGBATfaL6OoBr4qotf_W6FrCnTiCR7Bidd7BgaWenU

where 

code -> Authorization code (Required)

Step 5: To get the access token, Click on Exchange authorization code for tokens button and you will get the access and refresh token.



Check Request/Response section, Playground hits TOKEN ENDPOINTS to get the access token.

Token request:

We hit token endpoint to obtain an access token by exchanging the Auth code.

code=4%2F4by6pl_Bc22NnjpiCMvqrW4R2SL4oI7OjioWBHqWrD0&redirect_uri=https%3A%2F%2Fdevelopers.google.com%2Foauthplayground&client_id=407408718192.apps.googleusercontent.com&client_secret=************&scope=&grant_type=authorization_code

where
client_id -> The Id issued to this application by Authorization server at the time of registration. (Required)
client_secret -> The key secret issued to this application by Authorization server at the time of registration. (Required)
Grant_type -> Must be set to authorization_code. (Required)
Code -> The Authorization code received by the Authorization server.
(Required)

redirect_uri -> URI registered on the authorization server as a RedirectURI or callback URL. (Required)

Token Response:

The token response contains an access token along with other information in a JSON format.
{
  "access_token": "ya29.GlvMBFEQ8efg2id-lwfWJJIZl0_7rlCRyCKVWvv3v_cXIUlnYXVn6D04nUEIh9AFB65pdZcfms5TaDz692-2hmadFg0o6R1X7hdYUKuFwA9v2NvXqiLwOIFpUJlV",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "1/KVEh2UxFjMt5zynnbm9qajpnkDsREQTA3kldrAvcqKQ",
  "id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjhiNmE3ZDhhM2I0NTQ4YWU1MjBmZDJkMTY2ZWEzN2U2ZGRjY2JkOWYifQ.eyJhenAiOiI0MDc0MDg3MTgxOTIuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJhdWQiOiI0MDc0MDg3MTgxOTIuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJzdWIiOiIxMDUyOTA1MTEwNTU1NTA4NjY0ODciLCJhdF9oYXNoIjoiODVIUHJYSnZiWTNmN0FTOEg2VjBYZyIsImlzcyI6Imh0dHBzOi8vYWNjb3VudHMuZ29vZ2xlLmNvbSIsImlhdCI6MTUwNTkwNzc3MCwiZXhwIjoxNTA1OTExMzcwLCJuYW1lIjoiYWJkdWwgd2FoZWVkIiwicGljdHVyZSI6Imh0dHBzOi8vbGgzLmdvb2dsZXVzZXJjb250ZW50LmNvbS8tcDRVaEFJTUNkWkUvQUFBQUFBQUFBQUkvQUFBQUFBQUFCQ0UvTy1YUnEyUFVhYW8vczk2LWMvcGhvdG8uanBnIiwiZ2l2ZW5fbmFtZSI6ImFiZHVsIiwiZmFtaWx5X25hbWUiOiJ3YWhlZWQiLCJsb2NhbGUiOiJlbi1HQiJ9.sS2Du_uR0Y-Sr2BlxBkbYSbzNfXDLy_Baj1ZbX21x-tWUHTe5R9v9ZR8S7gwfmVjAPAjHm-ivQg4aOBzQs8U9YmCei2tg1vLFTg51KsTWXK6u4WEbgHQQaPOORAfeKrZtKaUjvQgTKy007Dqdv_nzT6dt9b-vezTDLHX-fV9lx-k_-ApD9BKdrBjsqx8tAJ1cC_vg4NY_M--6ztYSf8xKG_aAF296Mq_aUakVGSl2pA5n3k0SMXyJlkIaWCilz2jQjBt_Hi_zeKdezCIU4jHTr8lstyz_SV9V2nueWV7n82K2RzS3uo-PtMDUWceNRr0r6dhWh_JxXivCqH2twh9pw"
}

Where
access_token -> token using which you can access the user details from resource server.
token_type -> define the nature of token
expire_in -> number of seconds after which the access token get expired.

refresh_token -> using refresh token, we can get new access token once the above access token is no longer valid.

Step 6: Select V2 UserInfo from list possible operations to get the user profile.


Step 7: Click on Send the request button and it will access the user profile by passing access token as authorization bearer in the headers and display it in JSON format.


Conclusion: Google playground is an amazing tool to learn OAuth flow with Google as well as with custom application. If you are planning to build your Authorization server then you can use it as a testing tool as Google playground is a standard OAuth Client web application.


If you need an idea on how can we get it done the same thing via JAVA web application then you must check my blog over here. I have done something similar where my Service provider is Salesforce instead of Google.

Friday, September 15, 2017

Registering an Application with Facebook

This guide walks you through the steps of registering an application to integrate with Facebook.
Register a new application

From http://developer.facebook.com, click on "My Apps" at the top of the page to go to the application dashboard. The dashboard shows a list of applications that the developer has already created or you can create a new one by clicking on Add a new App. 

A dialog prompts you to name your application.

Enter Display Name, Contact Email and Choose a category from drop down list and click on Create App ID. After you click, Facebook performs a Captcha check to verify that you’re not setting up applications through an automated process.

Once you’ve satisfied the verification process, your application is created. The next page you see is your application’s application page.

Click on the Settings button and it will open you a setting page of your application.

Now we can configure various details about our application. The choices you make here depend on what kind of application you plan to build and what you want your application to do. For IAM, we just need to add App Domains and Site URL. Click on + Add Platform and select Platform as Website and enter your Site URL. Site URL is shibboleth Idp URL and App Domains is the domain name of the URL.

and click on Save Changes. 

The main thing to note from the application settings page is the App ID and App Secret near the top. These values are your application’s credentials to Facebook. We need these credentials to connect to facebook via Shibboleth Idp.

and the last step, go to App Review → drag button to the left to make your application public. You will see message as "your app is currently live and available to the public"


Wednesday, February 22, 2017

OAuth vs SSO: Which One Should I Use?

Currently, I am working on one project which provided me a lot of opportunities to learn about OAuth 2.0 and SAML and better understanding on which one to choose for SSO strategy.
I am choosing this topic because most of the people get confused between these two. While they have some similarities but they are very different too and to put it one line. I would say “OAuth is not Single Sign-On”


What is the difference between OAuth 2.0 and SSO?



OAuth (Open Authorization) is a standard for authorization of resources. It does not deal with authentication. It allows secure authorization in a simple and standard method from web, mobile and desktop applications.

If you try to log into Stack Overflow using Facebook, you’ll be redirected to Facebook’s website and will see something like the following:



Once authenticated with Facebook, it will ask for Stack Overflow’s permission to access your resources like your name, Email id, Profile picture and so on. This is an authorization request like what Stack Overflow can do and what cannot do?

SAML: Security Assertion Markup Language is an XML-based open standard data format for exchanging authentication and authorization data between parties, in particular, between an identity provider and a service provider. It is an umbrella standard that encompasses profiles, bindings and constructs to achieve Single Sign-On (SSO), Federation and Identity Management.

SSO is an authentication/authorization flow through which a user can log into multiple services using the same credentials.
For instance, at your company where we have various applications like leave application, lunch application, career application and so on and we can configure all these applications to one Active Directory for authentication. Another example can be Atlassian account where you once logged in can use their other applications like Bamboo, JIRA, Confluence and so on.

Both examples represent SSO.

One of the main benefits to using SSO is that your users have only a single account and password to remember which gets them into all of their services.


Conclusion: When Should I Use Which?


  • If your use case requires a single account to log into many applications, then go with SSO like your internal company applications.
  • If your use case involves providing access (temporarily or permanent) to resources (such as accounts, pictures, files etc.), then use OAuth.
  • If your use case requires a centralized identity source, then use SSO.
  • If your case requires to have accounts on many different services, and selectively grant access to various services, use OAuth

Friday, February 14, 2014

Working of WSO2 Identity Server

To enable OAuth support for your client application, First we need to register our application on WSO2 Identity Server.

Step to register Client App on WSO2 IS :

  1. Goto Management Console and Enter your username and password. By default its “admin”.
  2. Click Main button and then OAuth in Manage menu.
  3. Click on the Register New Application link on the OAuth Management page.



  1. Select OAuth 2.0 as the OAuth Version. Enter Application Name and your Callback Url. For this app to work use http://localhost:8080/playground/oauth2client.


  
   5. Click on Add button , you will see your application under the OAuth                Management Page.





  1. Click on the WSO2 application and copy the Client ID, Client Secret, Access Token URL and Authorize URL. We need these values for our web app.


You are done with the registration part..!!!



Sample App with WSO2 Identity Server :

Download the sample app from here and host it in Tomcat. You can see the app running at http://localhost:7070/playground.
  1. Click on Import Photos






  1. Select the Grant Type as “authorization code”. Enter Client Id , Authorize Endpoint that we got while registering our Application. Scope is Optional and click on Authorize.


3. WSO2 Identity Server requests access to noscope, After login click on Approve.


4. You will get authorization code, Now enter the value for the Access Token Endpoint and Client Secret and click Get Access Token.

5 . Once you get access token, Click on “Get Photo”.




How to retrieve Facebook profile using Apache Oltu

This tutorial shows you the basic of OAuth using Apache Oltu (Formely known as Apache Amber). We have created a Java Web Application that authenticates the user to Facebook via OAuth 2.0 and retreive the protected resources from Facebook.

Setup :
  • SSL enabled Tomcat Server as we have deployed our Web Application on tomcat. Click here for instruction on How to enable SSL on Apache Tomcat 7.0
  • Registered Facebook Application. Check here for instruction on How to register App on Facebook.
  • Download the OltuClientFB Application from the GIT repository.
  • If you are using Maven then add below dependency or download Apache Oltu client jars :
    <dependency>
      <groupId>org.apache.oltu.oauth2</groupId>
      <artifactId>org.apache.oltu.oauth2.client</artifactId>
    </dependency>

Run the Project :

Check out the project from the above URL, import into the eclipse and Run as a Server.

Navigate your browser to https://localhost:<port>/OltuClientFB. You will see the following page:





Click on the link and it will take you the Facebook page for Authentication :


Once you are login into Facebook, It will ask you to allow the Oauth application to access your private data:



Once you click on “Okay” button. It will display your profile detail like UserId, Name etc.



Code Description :

OAuthServlet.Java

In the Servlet initParams, We have defined the clientId, clinetSecret and the redirectUri, You can change it as per your Apps.
// clientId is 'App ID '
@WebInitParam(name = "clientId", value = "YOUR_CLIENT_ID"),
// clientSecret is 'App Secret'
@WebInitParam(name = "YOUR_CLIENT_SECRET", value = "70ba69525274876dce9697ad183a9051"),
// This must be identical to 'Valid OAuth Redirect URI's'
@WebInitParam(name = "redirectUri", value = "https://localhost:7443/OltuClientFB/OAuthServlet/callback"),})

The Java Web Application act as a third-party website or termed as “client” which operate on behalf of a user. It first sends the request to Facebook which authenticates the user, obtain the user's authorization(i,e Approve/Deny page) and issues an access token which client can use while interacting with the resource server i,e Facebook to access public profile of the user.

End user Authorization request :


Created the End User Authorization Request by providing end-user authorization URI at the Authorization Server (e.g. Facebook), application's client id and a redirect URI in order to receive the authorization code. Apache Oltu has an enum OAuthProviderType for authorization and token endpoints of common OAuth 2 providers like Facebook.

OauthClientRequest authClientRequest = OAuthClientRequest
.authorizationProvider(OAuthProviderType.FACEBOOK)
.setClientId(clientId).setRedirectURI(redirectUri)
.buildQueryMessage();

The above code will produce an OAuth request where all the parameters are encoded in the URL query.

response.sendRedirect(authClientRequest.getLocationUri());

Get Authorization Code from redirect URI :

Once the user grants permission for your client application, then the Facebook will redirects the user to redirectUri with the code in the request parameter.


OAuthAuthzResponse oar = OauthAuthzResponse.oauthCodeAuthzResponse(request); code = oar.getCode();

Exchange OAuth code for an access token :


Apache Oltu has two different classes to parse the access token response. Facebook’s response is not fully compliant with the final version of the OAuth 2 specification, but it can be parsed using the class GitHubTokenResponse.



OauthClientRequest authClientRequest = OAuthClientRequest.tokenProvider(OAuthProviderType.FACEBOOK)
.setGrantType(GrantType.AUTHORIZATION_CODE)
.setClientId(clientId).setClientSecret(clientSecret)
.setRedirectURI(redirectUri).setCode(authorizationCode)
.buildBodyMessage();
//create OAuth client that uses custom http client under the hood
oAuthClient = new OAuthClient(new URLConnectionClient());
GitHubTokenResponse oAuthResponse = oAuthClient.accessToken(authClientRequest,
GitHubTokenResponse.class);
String accessToken = oauthResponse.getAccessToken();

Get Facebook profile data :

OAuthClientRequest bearerClientRequest = new OAuthBearerClientRequest("https://graph.facebook.com/me").setAccessToken(accessToken).buildQueryMessage();
OAuthResourceResponse resourceResponse oAuthClient.resource(bearerClientRequest, OAuth.HttpMethod.GET,
OauthResourceResponse.class);

DisplayFacebookProfile.Java 
This class will display the user profile on the UI.


Summary :

This application demonstrates the basic of OAuth 2.0 using Apache Oltu i,e how to authenticates the user and retreive the protected resources from Facebook.

Resources :

https://cwiki.apache.org/confluence/display/OLTU/OAuth+2.0+Client+Quickstart

Code download link:
https://drive.google.com/file/d/0B7WKU816EmtaSUw3UmpsWUljWk0/view?usp=sharing

How to register App on Facebook

Steps to create Apps on Facebook :


Registration Page
  • Enter the Display Name. This is required. 
  • Enter Namespace. (Optional)
  • Choose a Category and then click on Create App button. After verifying captcha It will show you the App ID and App Secret which is nothing but ClientId and ClientSecret . Check below screenshot :




  • Select “Settings” and then click on “Advance” tab.
  • Scroll down and enter your callback URL in “Valid Oauth redirect URIs” and then click on “Save Changes button to save your apps.





Congratulation!!! You have created your Apps on Facebook.

Thursday, February 21, 2013

How to integrate Web Application with Salesforce via Oauth

This tutorial shows you the basic of Oauth. We have created a Java Web Application that authenticates the user to salesforce via Oauth 2.0 and then we have performed few CRUD operation via the new API.

Setup:

  • SSL enabled Tomcat Server as we have deployed our Web Application on tomcat. Click here for instruction on How to enable SSL on apache Tomcat 7.0
  • Salesforce Remote Access Application. Click here for instruction on How to create Remote Access Application on Salesforce?
  • Download the application from here and change the name to Services.

Run the Project:

Check out the project from the above URL, import into the eclipse and Run as a Server.

Navigate your browser to https://localhost:8443/Services. You will see the following page:



Click on the link and it will take you the salesforce page for Authentication :





Once you are login into salesforce, It will ask you to allow the Oauth_Apps to access your data:





After clicking on “Approve”button, You will see the below page with few CRUD operation output :


Note : You have provided your credentials to the salesforce.com website not to the requesting application. This is Oauth in Action. Once you are authorize accessing to your data, The control will return back to your application with salesforce.com generated token using which you can interact with the salesforce data.

Code Description:

OauthServlet.Java

In the Servlet initParams, We have defined the clinetSecret, clientId and the redirectUri, You can change it as per your remote application.
@WebInitParam(name = "clientId", value = "3MVG9Y6d_Btp4xp5hntckvnA5QVKsxlc4RUx9CbJndYCQQS4oO7jHAVspS0WdeCXBJlMXO1e9hwQSCjCBB71H"),
// clientSecret is 'Consumer Secret' in the Remote Access UI
@WebInitParam(name = "clientSecret", value = "4518803906379506686"),
// This must be identical to 'Callback URL' in the Remote Access UI
@WebInitParam(name = "redirectUri", value = "https://localhost:8443/Services/OAuthServlet/callback"),
@WebInitParam(name = "environment", value = "https://login.salesforce.com"), })

Here our Java Web Application act as a third-party website or termed as “client” which operate on behalf of a user. It first sends the request to salesforce.com which authenticates the user, obtain the user's authorization(i,e Approve/Deny page) and issues an access token which client can use while interacting with the resource server I,e salesforce instance.


When the Servlet initializes, it constructs authUrl, to which it redirects the user to authenticate and authorize access to data:
try {
authUrl = environment+ "/services/oauth2/authorize?response_type=code&client_id="
+ clientId + "&redirect_uri="+ URLEncoder.encode(redirectUri, "UTF-8");}

The authUrl contains the configuartion which identifies the salesforce remote application.It also creates the tokenUrl which it uses to obtain the access token.
The response.sendRedirect(authUrl) authenticates the users, obtains authorization for the web app to access the user’s data(first time) and then redirects the user back to redirectUri: https://localhost:8443/Services/OAuthServlet/callback


When control returns to the Servlet, we use the returned data to build a POST request and send it to tokenUrl and we get the response(access token and instance Url) from authorization server in JSON format.

TestApi.java

As we have access token, Here we have just perform few CRUD operation i,e showAccounts, createAccount,deleteAccount and updateAccounts. In every HttpClient calls, we set a request header, Authorization to the value OAuth, followed by a space, and the access token. It is essential to do this for every interaction with the REST API; failure to do so results in a 401 ‘Unauthorized’ error when submitting the request.

Summary:

The application demonstrates how to authenticate and retrieve an access token using Oauth 2.0 and how we can do perform CURD operation with the help of access token.

References:

http://oauth.net/2/
http://wiki.developerforce.com/page/Getting_Started_with_the_Force.com_REST_API

Monday, February 4, 2013

How to create Remote Access Application on Salesforce?

Before I'll start with how to create Remote Access Application. First let me explain what is actually Remote Access Application.

What is Remote Access Application?
A remote access Application is an application external to salesforce that uses the Oauth protocol to verify both the salesforce user and the external data. All remote access applications have been integrated with salesforce, such that they can access a subset of your salesforce data once you explicitly grant each application permission.

How to create Remote Access Application?

To create an Remote application, You must have your developer account, If you don’t have it then You can create it from here.

Step to create your First Remote Access Application:
  1. Login to salesforce.com then click Your Name |Create | Apps and click on “new” button. Check below screenshot :
      

    When you click on new button, you will see a page like this:



  1. Enter the name of the Application. This is required.
  2. Enter the specify Callback URL which is also required. It represents the URL that the user will be returned to after they approve access for the application. Mostly It uses HTTPS protocol.
  3. Enter your Contact Email. Contact Email is required.
  4. Now Save the Remote Access Application.
Once you saved the application you will get the generated consumer key and consumer secret as shown below:





Note : Later, If you change the name of the application, the consumer key and consumer secret are not regenerated. It will be same as it was generated on the first time.
 
Congratulation!!! You have created your first Remote Access Application.

How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...