技术控

    今日:0| 主题:63445
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] OpenID Connect for User Authentication In ASP.NET Core

[复制链接]
懂我与否 发表于 2016-10-5 09:39:45
388 6
In the age of the “personalized web experience”, authentication and user management is a given, and it’s easier than ever to tap into third-party authentication providers like Facebook, Twitter and Google. And it’s not just the wild, wild web that needs it. Businesses need ways to secure their APIs and identify users logged into their applications.
   OpenID Connect is a protocol for authenticating users, built with the latest in security technologies. It is a specification by the OpenID Foundation describing the best way for the authentication “handshake” to happen. It lays out what am Identity Provider needs to provide in order to be considered “ OpenID Connect Certified ” and that makes it easier than ever to consume authentication as a service.
  Why Not Use The Built-In Authentication Providers?

   The authentication providers built into ASP.NET Core are outstanding, but there are some shortcomings. First, OAuth is NOT an authentication protocol . I know what you’re thinking: “What?!!?” But it’s not. It is an Authorization Specification, which many modern authentication protocols are built on.
  Second, while OAuth does a great job of providing the necessary information for consumers to make authorization decisions, it says nothing about how that information will be exchanged securely. This led to every authentication provider having their own way of exchanging the OAuth information, which has led to a few well-publicized hacks. OpenID Connect fixes these problems by providing an authentication protocol that describes exactly how the exchange of authorization information happens between a subscriber and their provider.
  So let’s see how this works.
  Nothing Up My Sleeve

   We’ll be using Visual Studio Code and the command line (don’t look at me like that, I like coding on my Mac). First, get the dotnet command-line program and Yeoman , then we can get a basic application started by using the Yeoman generator from OmniSharp . After running the yo aspnet command, it asks a couple of questions about the app we want to create.
   

OpenID Connect for User Authentication In ASP.NET Core

OpenID Connect for User Authentication In ASP.NET Core

  The most important is to choose: Web Application Basic (without Membership and Authorization). We’re going to do those ourselves.
  It should take a few seconds, and you’ll have a simple ASP.NET Core app ready to go. Just follow the instructions that Yeoman displays at the end of the creation to get the app up and running.
  Getting an Identity Provider

   Now we need an Identity Provider. We’re going to use Google , so we need to set up a client on Google’s Developer Dashboard . Once you’re logged in to your account, select the drop-down at the top right where your account information is and choose “Create a project…” from the bottom of the list.
   

OpenID Connect for User Authentication In ASP.NET Core

OpenID Connect for User Authentication In ASP.NET Core

  Choose a name for the project (it could be the same as your ASP.NET project), click the create button and Google should start creating the new project for you.
  When the project is created, you should see a Library page. We’ll be using the Google+ API in the Social APIs group. At the very top, click the “ENABLE” link and when it’s done, you should see a box show up right below the button.
   

OpenID Connect for User Authentication In ASP.NET Core

OpenID Connect for User Authentication In ASP.NET Core

  Click the button that says “Go To Credentials” to add credentials to your project. The Google+ API is already selected as the API we’ll be using, but we want to tell Google that we’ll be calling the API from a Web server (e.g. node.js, Tomcat) and that we’ll be accessing User data.
  Once you’ve done that, click the “What credentials do I need?” button and it will take you to the screen to create an OAuth 2.0 Client ID. You can call it whatever you like (or just leave it as is). The important parts are the origin and redirect URLs. We’ll use the local URL where the sample app runs for the origin and the same local URL with a path of /signin-oidc for the redirect URI and then click the “Create client ID” button.
   

OpenID Connect for User Authentication In ASP.NET Core

OpenID Connect for User Authentication In ASP.NET Core

  On the Consent Screen, the only thing we need to add is the Product name shown to users. You can name it whatever you like, even the same thing as your Project. When you click the continue button, you’ll see a Download credentials section. Copy the Client ID for use in our application, and then click the done button. You might think that’s it, but we need one more piece of information from the project. Click on the link for the OAuth 2.0 Client we just created and copy the client secret from that page.
  Now we’re ready to set up the authentication in our application!
  Getting Auth’d with OpenID Connect

  When you open your application in Visual Studio Code, you’ll notice that there is a project.json file. We’ll need to make some quick changes to that to get some dependencies we’ll need to make this work. In the dependencies section of the project.json document add:
  1. "Microsoft.AspNetCore.Authentication.JwtBearer": "1.0.0",
  2. "Microsoft.AspNetCore.Authentication.Cookies": "1.0.0",
  3. "Microsoft.AspNetCore.Authentication.OpenIdConnect": "1.0.0",
复制代码
  This will allow us to use JSON Web Tokens for authorization information, get them from the OpenID Connect provider (Google in our case) and store them in cookies for session management. You’ll need to run a quick dotnet restore command but don’t worry, once you save the file, VS Code will give you a button to click so you don’t have to go back to the command line. Now we’ll enter the meat of the OpenID Connect authentication.
  Open the Startup.cs file, and on the first line of the Configure method add:
  1. JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
复制代码
This will clear any previous claim type maps. Then, between the app.UseStaticFiles(); and app.UseMvc(…); add:
  1. app.UseCookieAuthentication(new CookieAuthenticationOptions(){
  2.     AuthenticationScheme = "Cookies",
  3.     AutomaticAuthenticate = true
  4. });
复制代码
This tells the application that we want to store our session tokens in cookies. Then, we need to add the authentication instructions.
  1. app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions(){
  2.     AuthenticationScheme = "oidc",
  3.     SignInScheme = "Cookies",
  4.     Authority = "https://accounts.google.com",
  5.     ResponseType = "code id_token",
  6.     ClientId = "{Replace with your Coogle Client ID}",
  7.     ClientSecret = "{Replace with your Google Client Secret}",
  8.     GetClaimsFromUserInfoEndpoint = true,
  9.     SaveTokens = true
  10. });
复制代码
This is the important part, so we’ll go through it line by line.
   The AuthenticationScheme gives out scheme a name and will be used to build the default callback url (~/sign-in/oidc).
   The SignInScheme is used to set the sign-in middleware.
   The Authority identifies the authorization endpoint for our Identity Provider. It is discoverable as part of the OpenID specification, and is located at: https://accounts.google.com/.well-known/openid-configuration.
   The ResponseType is also specified in that document under “response_types_supported”. This tells the application I am expecting a coded token back from the provider.
   The ClientId , and ClientSecret are pretty self-explanatory. We got them from Google when we signed up.
   The GetClaimsFromUserInfoEndpoint setting tells the provider that if we’re successful authenticating, go ahead and make a call to the userinfo_endpoint (specified in the configuration document at the same URL we got the authorization_endpoint and the response_types_supported from).
  Finally, we tell the application to save the token once it comes back from the provider.
   That’s all there is to it, but how do we know it’s working? We could hook up a login form but there is an easier way.
  Checking Our Work

   All we really need to do is add an [Authorize] attribute to a controller method. That will certainly show us that it is going to the login on the provider, but it won’t show us what the provider is sending back. Let’s create page that will show us that information so we can make sure we’re getting what we think we’re getting from the provider.
  Add a “Secure” method to the HomeController.cs controller.
  1. [Authorize]
  2. public asyncTask<IActionResult> Secure()
  3. {
  4.     return View();
  5. }
复制代码
Then create a view to return:
  1. @{
  2.     ViewData["Title"] = "Security";
  3. }
  4. <h2>Secure</h2>
  5. <dl>
  6.     @foreach (var claimin User.Claims)
  7.     {
  8.         <dt>@claim.Type</dt>
  9.         <dd>@claim.Value</dd>
  10.     }
  11. </dl>
复制代码
This will just loop through the claims and output them.
  When you view the page, you should now see a list of the claims on the secure page.
  Congratulations, you just set up OpenID Connect for authentication in your ASP.NET Core app!
  Learn More

  Interested in learning more about user authentication and token management in ASP.NET Core? You’re in the right place! Check out these awesome resources:
   Token Authentication in ASP.NET Core
   Tutorial: Build an ASP.NET Core Application with User Authentication
   Getting Started with SAML Single Sign-On in .NET
   If you have any questions, comments, or suggestions, feel free to reach out to me by email or via Twitter @leebrandt .
guoshiqiang 发表于 2016-10-5 12:10:39
每天只签到不留言的,升级永远没有见贴就留言的快。说明:”复制粘贴很重要!
回复 支持 反对

使用道具 举报

phzce 发表于 2016-10-5 15:40:23
我也顶起出售广告位
回复 支持 反对

使用道具 举报

挚爱红颜 发表于 2016-10-6 20:38:45
占位编辑
回复 支持 反对

使用道具 举报

哇哒嘻哇阿啦嗒 发表于 2016-10-8 04:37:46
小鲜肉心塞
回复 支持 反对

使用道具 举报

14984984 发表于 2016-11-11 20:03:50
兄弟我先抛块砖,有玉的尽管砸过来。
回复 支持 反对

使用道具 举报

yinyumei 发表于 2016-11-19 18:07:03
为何要放弃治疗?
回复 支持 反对

使用道具 举报

我要投稿

回页顶回复上一篇下一篇回列表
手机版/c.CoLaBug.com ( 粤ICP备05003221号 | 粤公网安备 44010402000842号 )

© 2001-2017 Comsenz Inc.

返回顶部 返回列表