Token Based Authentication in Web API 2

原文地址: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 == "[email protected]")
  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", "[email protected]"},
  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.

时间: 2024-07-30 01:30:09

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

Claims Based Authentication and Token Based Authentication

基于声明的认证方式,主要用于第三方认证. A claim is a statement that one subject makes about itself or another subject. The statement can be about a name, identity, key, group, privilege, or capability, for example. Claims are issued by a provider, and they are given on

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 separate the Authorization Server and the Resource Server by unifying the "decryptionKey" and "validationKey" key values in machineKey node

如何调用基于TOKEN签名验证ASP.NET Web API

1.首先获得Token 2.通过Token调用

Implement JSON Web Tokens Authentication in ASP.NET Web API and Identity 2.1

http://bitoftech.net/2015/02/16/implement-oauth-json-web-tokens-authentication-in-asp-net-web-api-and-identity-2/ Currently our API doesn’t support authentication and authorization, all the requests we receive to any end point are done anonymously, I

在ASP.NET Web API 2中使用Owin OAuth 刷新令牌

在上篇文章介绍了Web Api中使用令牌进行授权的后端实现方法,基于WebApi2和OWIN OAuth实现了获取access token,使用token访问需授权的资源信息.本文将介绍在Web Api中启用刷新令牌的后端实现. 本文要用到上篇文章所使用的代码,代码编写环境为VS 2017..Net Framework 4.7.2,数据库为MS SQL 2008 R2. OAuth 刷新令牌 上文已经搞了一套Token授权访问,这里有多出来一个刷新令牌(Refresh Token),平白添加程序

Web API 身份验证 不记名令牌验证 Bearer Token Authentication

1. Startup.Auth.cs文件 添加属性 public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; } 添加静态构造函数 /// <summary> /// 构造函数 /// </summary> static Startup() { OAuthBearerOptions = new OAuthBearerAuthenticationOptions(); }

asp.net Web API 身份验证 不记名令牌验证 Bearer Token Authentication 简单实现

1. Startup.Auth.cs文件 添加属性 1 public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; } 添加静态构造函数 1 2 3 4 5 6 7 /// <summary> /// 构造函数 /// </summary> static Startup() {     OAuthBearerOptions = new OAuthBearerAuthent

web api token验证理解

最近一直在学习web api authentication,以Jwt为例,可以这样理解,token是身份证,用户名和密码是户口本,身份证是有有效期的(jwt 有过期时间),且携带方便(自己带有所有信息 self contained),户口本不会过期(用户名和密码什么时候都有用),携带不方便(用户名和密码从数据库验证),jwt同样也有身份证的缺点,丢了别人有些地方可以用,户口本改名字了,身份证还可以用(同样,用户名和密码修改后jwt不修改).针对身份证的缺点,可以设置较短过期时间,另外token

Web API之认证(Authentication)及授权(Authorization)【一】(十二)

前言 无论是ASP.NET MVC还是Web API框架,在从请求到响应这一过程中对于请求信息的认证以及认证成功过后对于访问页面的授权是极其重要的,用两节来重点来讲述这二者,这一节首先讲述一下关于这二者的一些基本信息,下一节讲通过实战以及不同的实现方式来加深对这二者深刻的认识,希望此文对你有所收获. Identity Identity代表认证用户的身份,下面我们来看看此接口的定义 public interface IIdentity { // Properties string Authenti