原文地址: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. 决战大数据之三-Apache ZooKeeper Standalone及复制模式安装及测试

    决战大数据之三-Apache ZooKeeper Standalone及复制模式安装及测试 [TOC] Apache ZooKeeper 单机模式安装 创建hadoop用户&赋予sudo权限, ...

  2. 为你的网页图标(Favicon)添加炫丽的动画和图片

    Favico.js 在让你的网页图标显示徽章,图像或视频.你设置可以轻松地在网页图标中使用动画,可以自定义类型的动画,背景颜色和文字颜色.它支持的动画,像幻灯片,渐变,弹出等等. 您可能感兴趣的相关文 ...

  3. RequireJS使用注意地方

    使用RequireJS做异步模块加载,有几点值得注意的地方: 1.模块定义两种写法 1. 存在依赖的函数式定义 如果模块存在依赖:则第一个参数是依赖的名称数组:第二个参数是函数,在模块的所有依赖加载完 ...

  4. BFC布局原理

    写这篇博客的初衷其实是在解决浮动的时候看到的这个方法,就想着BFC是什么,为什么可以清除浮动.结果不看不知道,一看越看越不明白,潜下心来研究看看,总结一下学习心得. 1.BFC是什么 BFC就是Box ...

  5. 全信号高清DVI编码器|上海视涛科技

    高清DVI编码器(E700)简介 高清DVI编码器是上海视涛科技出品的高性能全信号DVI编码产品.该DVI编码器是上海视涛科技完全自主研发,并适用于DVI信号的编码采集及网络传输的专用硬件设备.可兼容 ...

  6. IOS安全测试

    1.本地存储安全 配置文件 缓存 数据库 测试数据 证书数据 2.网络通信安全 http明文通信 https证书认证 敏感参数弱加密 加签/验签策略 外接第三方SDK 外发不明数据 3.源代码安全 日 ...

  7. 我理解的OAuth 1.0a 的验证过程

    故事梗概: 淘宝店主糖糖在京郊仓库存了一批大白兔奶糖,为了防止仓库钥匙被偷把仓库的钥匙交给了专业的钥匙保管员公司. 糖糖卖了一斤大白兔需要快递公司的小迪送货.快递员小迪找钥匙保管公司借钥匙,然后去京郊 ...

  8. 转使用chrome命令行:disable-web-security 实现浏览器跨域

    注意chrome 48 版本后此方法就不能用了 推荐一个新方式来实现本地跨域调试线上资源,搜索chrome插件 Allow-Control-Allow-Origin: *.https://chrome ...

  9. Android studio 如何查看当前git 分支的4种方式

    1.第一种       2.第二种       3.第三种 4.第四种       前面3种都是通过android studio 操作的. 第四种是通过命令行操作.(可以在 git bash 中输入命 ...

  10. Android终止线程的方法

    线程对象属于一次性消耗品,一般线程执行完run方法之后,线程就正常结束了,线程结束之后就报废了,不能再次start,只能新建一个线程对象.但有时run方法是永远不会结束的.例如在程序中使用线程进行So ...