原文地址:http://www.c-sharpcorner.com/uploadfile/736ca4/token-based-authentication-in-web-api-2/

Introduction
This article explains the OWIN OAuth 2.0 Authorization and how to implement an OAuth 2.0 Authorization server using the OWIN OAuth middleware.
The OAuth 2.0 Authorization framwork is defined in RFC 6749. It enables third-party applications to obtain limited access to HTTP services, either on behalf of a resource owner by producing a desired effect on approval interaction between the resource owner and the HTTP service or by allowing the third-party application to obtain access on its own behalf.
Now let us talk about how OAuth 2.0 works. It supports the following two (2) different authentication variants:

  1. Three-Legged
  2. Two-Legged

Three-Legged Approach: In this approach, a resource owner (user) can assure a third-party client (mobile applicant) about the identity, using a content provider (OAuthServer) without sharing any credentials to the third-party client.

Two-Legged Approach: This approach is known as a typical client-server approach where the client can directly authenticate the user with the content provider.

Multiple classes are in OAuth Authorization

OAuth Authorization can be done using the following two classes:

  • IOAuthorizationServerProvider
  • OAuthorizationServerOptions

IOAuthorizationServerProvider

It extends the abstract AuthenticationOptions from Microsoft.Owin.Security and is used by the core server options such as:

  • Enforcing HTTPS
  • Error detail level
  • Token expiry
  • Endpoint paths

We can use the IOAuthorizationServerProvider class to control the security of the data contained in the access tokens and authorization codes. System.Web will use machine key data protection, whereas HttpListener will rely on the Data Protection Application Programming Interface (DPAPI). We can see the various methods in this class.

OAuthorizationServerOptions

IOAuthAuthorizationServerProvider is responsible for processing events raised by the authorization server. Katana ships with a default implementation of IOAuthAuthorizationServerProvider called OAuthAuthorizationServerProvider. It is a very simple starting point for configuring the authorization server, since it allows us to either attach individual event handlers or to inherit from the class and override the relevant method directly.We can see the various methods in this class.

From now we can start to learn how to build an application having token-based authentication.

Step 1
Open the Visual Studio 2013 and click New Project.
Step 2
Select the Console based application and provide a nice name for the project.

 

Step 3
Create a Token class and Add some Property.

  1. public class Token
  2. {
  3. [JsonProperty("access_token")]
  4. public string AccessToken { get; set; }
  5. [JsonProperty("token_type")]
  6. public string TokenType { get; set; }
  7. [JsonProperty("expires_in")]
  8. public int ExpiresIn { get; set; }
  9. [JsonProperty("refresh_token")]
  10. public string RefreshToken { get; set; }
  11. }

Step 4

Create a startup class and use the IOAuthorizationServerProvider class as well as the OAuthorizationServerOptions class and set the dummy password and username. I have also set the default TokenEndpoint and TokenExpire time.

  1. public class Startup
  2. {
  3. public void Configuration(IAppBuilder app)
  4. {
  5. var oauthProvider = new OAuthAuthorizationServerProvider
  6. {
  7. OnGrantResourceOwnerCredentials = async context =>
  8. {
  9. if (context.UserName == "rranjan" && context.Password == "password@123")
  10. {
  11. var claimsIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
  12. claimsIdentity.AddClaim(new Claim("user", context.UserName));
  13. context.Validated(claimsIdentity);
  14. return;
  15. }
  16. context.Rejected();
  17. },
  18. OnValidateClientAuthentication = async context =>
  19. {
  20. string clientId;
  21. string clientSecret;
  22. if (context.TryGetBasicCredentials(out clientId, out clientSecret))
  23. {
  24. if (clientId == "rajeev" && clientSecret == "secretKey")
  25. {
  26. context.Validated();
  27. }
  28. }
  29. }
  30. };
  31. var oauthOptions = new OAuthAuthorizationServerOptions
  32. {
  33. AllowInsecureHttp = true,
  34. TokenEndpointPath = new PathString("/accesstoken"),
  35. Provider = oauthProvider,
  36. AuthorizationCodeExpireTimeSpan= TimeSpan.FromMinutes(1),
  37. AccessTokenExpireTimeSpan=TimeSpan.FromMinutes(3),
  38. SystemClock= new SystemClock()
  39. };
  40. app.UseOAuthAuthorizationServer(oauthOptions);
  41. app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
  42. var config = new HttpConfiguration();
  43. config.MapHttpAttributeRoutes();
  44. app.UseWebApi(config);
  45. }
  46. }

Step 5 

Add a controller inherited from API controller.

 
  1. [Authorize]
  2. public class TestController : ApiController
  3. {
  4. [Route("test")]
  5. public HttpResponseMessage Get()
  6. {
  7. return Request.CreateResponse(HttpStatusCode.OK, "hello from a secured resource!");
  8. }
  9. }

Step 6 

Now check the authorization on the basis of the token, so in the Program class validate it. 

  1. static void Main()
  2. {
  3. string baseAddress = "http://localhost:9000/";
  4. // Start OWIN host
  5. using (WebApp.Start<Startup>(url: baseAddress))
  6. {
  7. var client = new HttpClient();
  8. var response = client.GetAsync(baseAddress + "test").Result;
  9. Console.WriteLine(response);
  10. Console.WriteLine();
  11. var authorizationHeader = Convert.ToBase64String(Encoding.UTF8.GetBytes("rajeev:secretKey"));
  12. client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authorizationHeader);
  13. var form = new Dictionary<string, string>
  14. {
  15. {"grant_type", "password"},
  16. {"username", "rranjan"},
  17. {"password", "password@123"},
  18. };
  19. var tokenResponse = client.PostAsync(baseAddress + "accesstoken", new FormUrlEncodedContent(form)).Result;
  20. var token = tokenResponse.Content.ReadAsAsync<Token>(new[] { new JsonMediaTypeFormatter() }).Result;
  21. Console.WriteLine("Token issued is: {0}", token.AccessToken);
  22. Console.WriteLine();
  23. client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
  24. var authorizedResponse = client.GetAsync(baseAddress + "test").Result;
  25. Console.WriteLine(authorizedResponse);
  26. Console.WriteLine(authorizedResponse.Content.ReadAsStringAsync().Result);
  27. }
  28. Console.ReadLine();
  29. }

Output
When all the authentication of username and password is not correct then it doesn't generate the token.

When the Authentication is passed we get success and we get a token.


Summary
In this article we have understand the token-based authentication in Web API 2. I hope you will like it.

Token Based Authentication in Web API 2的更多相关文章

  1. Claims Based Authentication and Token Based Authentication和WIF

    基于声明的认证方式,其最大特性是可传递(一方面是由授信的Issuer,即claims持有方,发送到你的应用上,注意信任是单向的.例如QQ集成登录,登录成功后,QQ会向你的应用发送claims.另一方面 ...

  2. [转] JSON Web Token in ASP.NET Web API 2 using Owin

    本文转自:http://bitoftech.net/2014/10/27/json-web-token-asp-net-web-api-2-jwt-owin-authorization-server/ ...

  3. JSON Web Token in ASP.NET Web API 2 using Owin

    In the previous post Decouple OWIN Authorization Server from Resource Server we saw how we can separ ...

  4. Dynamics CRM模拟OAuth请求获得Token后在外部调用Web API

    关注本人微信和易信公众号: 微软动态CRM专家罗勇 ,回复233或者20161104可方便获取本文,同时可以在第一间得到我发布的最新的博文信息,follow me!我的网站是 www.luoyong. ...

  5. Asp.Net MVC webAPI Token based authentication

    1. 需要安装的nuget <package id="Microsoft.AspNet.Identity.Core" version="2.2.1" ta ...

  6. 基于JWT(Json Web Token)的ASP.NET Web API授权方式

    token应用流程 初次登录:用户初次登录,输入用户名密码 密码验证:服务器从数据库取出用户名和密码进行验证 生成JWT:服务器端验证通过,根据从数据库返回的信息,以及预设规则,生成JWT 返还JWT ...

  7. Token Based Authentication -- Implementation Demonstration

    https://www.w3.org/2001/sw/Europe/events/foaf-galway/papers/fp/token_based_authentication/

  8. Implement JSON Web Tokens Authentication in ASP.NET Web API and Identity 2.1 Part 3 (by TAISEER)

    http://bitoftech.net/2015/02/16/implement-oauth-json-web-tokens-authentication-in-asp-net-web-api-an ...

  9. 在ASP.NET Web API 2中使用Owin基于Token令牌的身份验证

    基于令牌的身份验证 基于令牌的身份验证主要区别于以前常用的常用的基于cookie的身份验证,基于cookie的身份验证在B/S架构中使用比较多,但是在Web Api中因其特殊性,基于cookie的身份 ...

随机推荐

  1. GJM : Unity3D结合ZXING制作二维码识别

    感谢您的阅读.喜欢的.有用的就请大哥大嫂们高抬贵手"推荐一下"吧!你的精神支持是博主强大的写作动力以及转载收藏动力.欢迎转载! 版权声明:本文原创发表于 [请点击连接前往] ,未经 ...

  2. 手机网游开发指南 - 需要多NB的技术

    Agent`K 似乎在三天打鱼N天晒网.只能呵呵了,懒散的家伙. 移动互联网越来越火,其中的网络游戏更是火,熊熊大火. 作为攻城师的你,作为小投资者的你,作为满脑子创意想要实现的你,肯定在四处打听:手 ...

  3. jQuery静态方法type使用和源码分析

    jQuery.type方法是检测数据类型的工具方法,在分析其用法之前先总结下js给我们提供了那些监测数据类型的方法: 一.typeof 操作符 下面是测试代码 var data=[],a='123', ...

  4. add host bat

    ::Author > mdt jindahao ::Data > @echo off title 添加记录到HOST--------Powerd by LoveQishi echo. ec ...

  5. git 上的pull request 是什么意思?

    1.git 上有常见的pull request 功能 2.pull request 的含义 解释一:    有一个仓库,叫Repo A.你如果要往里贡献代码,首先要Fork这个Repo,于是在你的Gi ...

  6. (20160604)开源第三方学习之CocoaLumberjack

    CocoaLumberjack是一个很好用的日志打印工具,它可以帮助我们把工程中的日志信息打印到终端或者输出到文件中. 地址:https://github.com/CocoaLumberjack/Co ...

  7. Android启动模式launchMode

    在Android里,有4种Activity的启动模式并分别介绍下: standard singleTop singleTask singleInstance AndroidManifest.xml配置 ...

  8. iOS本地推送与远程推送

    原文在此 分为本地推送和远程推送2种.可以在应用没有打开甚至手机锁屏情况下给用户以提示.它们都需要注册,注册后系统会弹出提示框(如下图)提示用户是否同意,如果同意则正常使用:如果用户不同意则下次打开程 ...

  9. 1.5 基础知识——GP2.3 提供资源(Resources) 与 GP2.4 分配职责(Responisbility)

    摘要: 没有资源和落实权责,将无法做好事情,这是很多公司很多人都懂的道理.但很多做CMMI改进的公司,号称很多核心人员负责过程改进,其实是兼职挂牌而已,有些甚至招聘应届生作为过程改进的主力…… 如此这 ...

  10. Newtonsoft.Json 把对象转换成json字符串

    var resultJson = new { records = rowCount, page = pageindex, //总页数=(总页数+页大小-1)/页大小 total = (rowCount ...