原文地址: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. cnodejs社区论坛5--话题详情

  2. Medoo个人修改版

    Medoo是一款轻量级的php数据库操作类,下面不会介绍Medoo的使用方法,想学习Medoo请前往官网自学:http://medoo.in/ 在接触Medoo之前,一直是用自己写的php数据库操作类 ...

  3. 用div和css样式控制页面布局

    <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...

  4. 【Spring】Spring框架之Struts2和Spring的优点

    Java Web开发使用Structs2和Spring框架的好处 今年我一直在思考web开发里的前后端分离的问题,到了现在也颇有点心得了,随着这个问题的深入,再加以现在公司很多web项目的控制层的技术 ...

  5. border-radius如何兼容IE

    目前而言firefox,opera,chrome等主流浏览器都已经支持border-radius属性,唯独IE8以及之前. 解决办法就是在用的border-radius属性的后面加上:behavior ...

  6. 自己动手打造WEB服务器 Windows + Apache + PHP + MySQL

    XWAMP并不打算打造一个多功能,零配置,方便调试的工具.XWAMP只是把原程序简单的组合在一起,利用CMD命令控制,真正的绿色版,只为了多学习点Windows + Apache + PHP + My ...

  7. 从0开始学angularjs-笔记04

    由于公司加班,刚到家不久,然而却毫无睡意,可能是老了吧--- 不废话了,没睡意那就做点有意义的事情吧,继续我们的angular学习之路,深夜博文,希望能造福大家! 这次我们来详细讲解angular的双 ...

  8. JavaScript常用技巧总结(持续添加中...)

    在我学习过程中收集的一些常用技巧: typeof x !== undifined 判断x是否已定义: x === Object(x)  判断x是否为对象: Object.keys(x).length ...

  9. 【问题及解决】fonts/fontawesome-webfont.woff2 404 (Not Found)

    问题: 虽然网页正常显示和运行,但是有2个字体文件出现404错误.像笔者这种强迫症是接受不了的. 解决: 因为笔者的服务器是虚拟主机,只需要在主机控制器平台添加对应的MIME类型即可. 这样服务器就支 ...

  10. ABAP 数据字典中的参考表和参考字段的作用

         ABAP数据字典中的参考表和参考字段的作用 大家最初在SE11中创建表和结构的时候都会遇到一个问题,如果设定了某个字段为QUAN或者CURR类型,也就是数量或金额的时候,总会要求输入一个参考 ...