Go An introduction-to-OAuth 2.0 using Facebook in ASP.

Source: Internet
Author: User
Tags oauth oauth provider openid

This article transferred from: http://andrewlock.net/an-introduction-to-oauth-2-using-facebook-in-asp-net-core/

The the next post in a series on authentication and authorisation in ASP. In this post I look in moderate depth @ The OAuth 2.0 protocol as it pertains to ASP. NET Core applications, walking Throu GH the protocol as seen by the user of your website as well as the application itself. Finally, I show how can configure your application to use a Facebook social login when you are using ASP. Tity.

OAuth 2.0

OAuth 2.0 is a open standard for authorisation. It is commonly used as a A-to-users to login-a particular website (say, catpics.com) using a third party account suc H as a Facebook or Google account, without has to provide catpics.com the password for their Facebook account.

While it's often used for authentication, being used to log a user on to a site, it's actually an Authorisa tionprotocol. We ' ll discuss the detail of the flow of requests in the next sections, but in essence, you as a user is providing Permiss Ion for the Catpics.com website to access some sort of personal information from the OAuth provider website (Facebook). So catpics.com are able to access your personal Facebook cat pictures, without have full access to your account, and with Out requiring provide your password directly.

There is a number of different ways you can use OAuth 2.0, each of which require different parameters and different us ER interactions. Which one should use depends on the nature of the application is developing, for example:

    • Resource Owner grant-requires The user to directly enter their username and password to the application. Useful when is developing a 1st party application to authenticate with your own servers, e.g. the Facebook mobile app Might use a Resource Owner Grant to authenticate with Facebook ' s servers.
    • Implicit grant-authenticating with a server returns an access token to the browser which can then be used to access Reso Urces. Useful for single Page applications (SPA) where communication cannot is private.
    • Authorisation Code grant-the typical OAuth Grant used by Web applications, such as you would use in your ASP. This is the flow I'll focus on for the rest of the article.
The authorisation Code Grant

Before explaining the flow fully, we need to clarify some of the terminology. This is where I often see people getting confused and the use of overloaded terms like ' Client '. Unfortunately, these is taken from the official spec, so I'll use them here as well, but for the remainder of the Artic Le I ' ll try and use disambiguated names instead.

We'll consider an ASP. Application that finds cats on your Facebook photos by using Facebook's OAuth authorisation.

    • Resource owner (e.g. the user)-this technically doesn ' t need to is a person as OAuth allows Machine-to-machine Authorisa tion, but for our purposes it's the end-user who is using your application.
    • Resource Service (e.g. the Facebook API server)-This is the endpoint your ASP. Application would call to access Facebo OK photos once it has been given an access token.
    • Client (e.g your app)-this is the application which are actually making the requests to the Resource service. So's this case it's the ASP. Application.
    • Authorisation server (e.g. the Facebook authorisation server)-This is the server, allows the user to login to their Facebook account.
    • Browser (e.g. Chrome, Safari)-not required by OAuth in general, but for our example, the Browser are the user-agent that The resource Owner/user is a using to navigate your ASP.
The flow

Now we had nailed some of the terminology, we can think about the actual flow of events and data when OAuth 2.0 was in use . The image below gives a detailed overview of the various interactions, from the user first requesting access to a PROTECTE D resource, to them finally gaining access to it. The flow looks complicated, but the key points to notice is the three calls to Facebook ' s servers.

As we go through the flow, we ' ll illustrate it from a user's point of view, using the default MVC template with ASP. Re Identity, configured to the use of Facebook as an external authentication mechanism.

Before you can use OAuth in your application, you first need to register your application with the authorisation server (F Acebook). There you'll need to provide a Redirect_uri and you'll be provided a client_id and Client_secret . The process is different-authorisation server so it's best-consult their developer docs for what go about t His. I ' ll cover how to register your application with Facebook later in this article.

Authorising to obtain an authorisation code

When the user requests a page in your app that requires authorisation, they'll be redirected to the login page. Here they can either login using a username and password to create an account directly with the site, or they can choose T o Login with a external provider-in this case just Facebook.

When the user clicks on the Facebook button, the ASP. Application sends a 302 to the user's browser, with a ur L similar to the following:

https://www.facebook.com/v2.6/dialog/oauth?client_id=CLIENT_ID&scope=public_profile,email&response_type=code&redirect_uri=REDIRECT_URI&state=STATE_TOKEN  

This URL is points to the Facebook authorisation server, and contains a number of replacement fields. Theclient_id and Redirect_uri is the ones we registered and were provided when we registered our apps in Facebook. The State_token is a CSRF tokens generated automatically by we application for security reasons (that I won ' t go into). Finally, the scope field indicates what resources we had requested access to-namely Public_profile an D their email.

Following this link, the user was directed in their browser to their Facebook login page. Once they has logged in, or if they is already logged in, they must grant authorisation to our registered ASP. ation to access the requested fields:

If the user clicks OK, then Facebook sends another 302 response to the browser, with a URL similar to the following:

http://localhost:5000/signin-facebook?code=AUTH_CODE&state=STATE_TOKEN  

Facebook has provided a Auth_code, along with the State_token we supplied with the initial redirect. The state can is verified to ensure that requests is not being forged by comparing it to the version stored in our Sessio n state in the ASP. Application. The Auth_code however is only temporary, and cannot are directly used to access the user details we need. Instead, we need to exchange it for a access token with the Facebook authorisation server.

Exchanging for an access token

This next portion of the flow occurs entirely server side-communication occurs directly between our ASP. and the Facebook authorisation server.

Our ASP. Application constructs a POST request to the Facebook Authorization server, to an Access token endpoint. The request sends our app's registered details, including the Client_secret and theAuth_token to the FAC Ebook endpoint:

POST /v2.6/oauth/access_token HTTP/1.1  Host: graph.facebook.com  Content-Type: application/x-www-form-urlencodedgrant_type=authorization_code&  code=AUTH_CODE&  redirect_uri=REDIRECT_URI&  client_id=CLIENT_ID&  client_secret=CLIENT_SECRET  

If the token is accepted by Facebook's authorisation server, then it'll respond with (among other things) an Access_ TOKEN. This access token allows our ASP. Application to access the resources (scopes) We requested at the beginning of the Flo W, but we don ' t actually has the details we need in order to create the Claims for our user yet.

Accessing the protected resource

After receiving and storing the access token, we have the app can now contact Facebook ' s Resource server. We is still completely server-side at the this point, communicating directly with Facebook ' s user information endpoint.

Our application constructs a GET request, providing the Access_token and a comma separated (and URL encoded) list of requested fields in the QueryString:

GET /v2.6/me?access_token=ACCESS_TOKEN&fields=name%2Cemail%2Cfirst_name%2Clast_name  Host: graph.facebook.com  

Assuming all is good, Facebook's resource server should respond with the requested fields. Your application can then add the appropriate Claims to the and ClaimsIdentity Your user is authenticated!

The description provided here omits a number of things such as handling expiration and refresh tokens, as well as the ASP. NET Core Identity process or associating the login to a email, but hopefully it provides a intermediate view of what's Happening as part of a social login.

Example usage in ASP.

If You're anything like me, when your first start looking at what's implement OAuth in your application, it all seems a bit Daunting. There's so many moving parts, different grants and backchannel communication The It seems like it'll be a chore to Setu P.

Luckily, the ASP. NET Core team has solved a massive amount of the headache for you! If you are using the ASP. NET Core Identity, then adding external providers is a breeze. The ASP. NET Core Documentationprovides a great walkthrough to creating your application and getting it all setup.

Essentially, if you have a app that uses ASP. NET Core Identity, all that's required to add Facebook authentication are to Install the package in your Project.json:

{  "dependencies": {    "Microsoft.AspNetCore.Authentication.Facebook": "1.0.0" }}

and configure the middleware in your Startup.Configure method:

PublicvoidConfigure(Iapplicationbuilder app, Ihostingenvironment env){app.Usestaticfiles(); App.Useidentity(); App.Usefacebookauthentication(NewFacebookoptions{AppId= Configuration["Facebook:appid"], Appsecret= Configuration["Facebook:appsecret"], Scope={"Email"}, fields={"Name","Email"}, Savetokens=True,}) usemvc (routes => {routes.maproute" default ": }) ;             

You can see we is loading the AppId and Appsecret (our client_id and Client_secret) from the configuration. On a development machine, these should is stored using the User Secrets Manager or environment variables (never commit th EM directly to your repository).

If you want to use a different external OAuth provider then you have several options. Microsoft provide a number of packages similar to the Facebook package shown which make integrating external logins . There is currently providers for Google, Twitter and (obviously) Microsoft accounts.

In addition, there is a number of open source libraries that provide similar handling of common providers. In particular, the AspNet.Security.OAuth.Providers repository have middleware for Providers like GitHub, Foursquare, Dropbo X and many others.

Alternatively, if a direct provider isn't available, you can use the genericMicrosoft.AspNetCore.Authentication.OAuth which these all build. For example Jerrie Pelser have an excellent post on configuring your ASP-Core application to use LinkedIn.

Registering your application with Facebook Graph API

As discussed previously, before you can use a OAuth provider, you must register your application with the provider to OBT Ain the client_id and Client_secret, and to register your Redirect_uri. I'll briefly show how to go on doing this for Facebook.

First, navigate to https://developers.facebook.com and login. If you had not already registered as a developer, you would need to register and agree to Facebook ' s policies.

Once A developer, can create a new Web application by following the prompts or navigating Tohttps://developers.faceboo K.com/quickstarts/?platform=web. Here you'll be prompted to provide a name for your Web application, and then to configure some basic details about it.

Once created, navigate to Https://developers.facebook.com/apps and click on your application ' s icon. You'll be taken to your app ' s basic details. Here's the can obtain the app Id and app Secret you'll need in your application. Make a note of them (store them using your secrets manager).

The last step was to configure the redirect URI for your application. Click on ' + Add Product ' at the bottom of the menu and choose Facebook Login. This would enable OAuth for your application, and allow you to set the Redirect_uri for your application.

The redirect path for the Facebook middleware is /signin-facebook . In my case, I is only running the app locally, so my full redirect URL is http://localhost:5000/signin-facebook .

Assuming everything is setup correctly, you should now being able to use OAuth 2.0 to login to your ASP. NET Core Application With facebook!

Final Thoughts

In the This post I showed how do you could use OAuth 2.0 to allow users to login to your ASP. NET Core application with Facebook a nd other OAuth 2.0 providers.

One point which is often overlooked are the fact that OAuth 2.0 are a protocol for performing authorisation, not authentication. The whole process is aimed in providing access to protected resources, rather than proving the identity of a user, which H As some subtle security implications.

Luckily there is a another protocol OpenId Connect, which deals with many of these issues, which essentially provides and Additional layer on top of the OAuth 2.0 protocol. I'll be doing a post on the OpenId Connect soon, but if you want to learn more, I ' ve provided some additional details below.

In the mean time, enjoy your social logins!

Further links
    • Https://github.com/aspnet-contrib/AspNet.Security.OAuth.Providers
    • Https://docs.asp.net/en/latest/security/authentication/sociallogins.html
    • Https://auth0.com/blog/authenticating-a-user-with-linkedin-in-aspnet-core/
    • Http://nat.sakimura.org/2011/05/15/dummys-guide-for-the-difference-between-oauth-authentication-and-openid/
    • http://nat.sakimura.org/2012/01/20/openid-connect-nutshell/
    • Http://www.thread-safe.com/2012/01/problem-with-oauth-for-authentication.html

[Go]an Introduction to OAuth 2.0 using the Facebook in ASP. NET Core

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.