原文地址: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:
- Three-Legged
- 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.
- public class Token
- {
- [JsonProperty("access_token")]
- public string AccessToken { get; set; }
- [JsonProperty("token_type")]
- public string TokenType { get; set; }
- [JsonProperty("expires_in")]
- public int ExpiresIn { get; set; }
- [JsonProperty("refresh_token")]
- public string RefreshToken { get; set; }
- }
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.
- public class Startup
- {
- public void Configuration(IAppBuilder app)
- {
- var oauthProvider = new OAuthAuthorizationServerProvider
- {
- OnGrantResourceOwnerCredentials = async context =>
- {
- if (context.UserName == "rranjan" && context.Password == "password@123")
- {
- var claimsIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
- claimsIdentity.AddClaim(new Claim("user", context.UserName));
- context.Validated(claimsIdentity);
- return;
- }
- context.Rejected();
- },
- OnValidateClientAuthentication = async context =>
- {
- string clientId;
- string clientSecret;
- if (context.TryGetBasicCredentials(out clientId, out clientSecret))
- {
- if (clientId == "rajeev" && clientSecret == "secretKey")
- {
- context.Validated();
- }
- }
- }
- };
- var oauthOptions = new OAuthAuthorizationServerOptions
- {
- AllowInsecureHttp = true,
- TokenEndpointPath = new PathString("/accesstoken"),
- Provider = oauthProvider,
- AuthorizationCodeExpireTimeSpan= TimeSpan.FromMinutes(1),
- AccessTokenExpireTimeSpan=TimeSpan.FromMinutes(3),
- SystemClock= new SystemClock()
- };
- app.UseOAuthAuthorizationServer(oauthOptions);
- app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
- var config = new HttpConfiguration();
- config.MapHttpAttributeRoutes();
- app.UseWebApi(config);
- }
- }
Step 5
Add a controller inherited from API controller.
- [Authorize]
- public class TestController : ApiController
- {
- [Route("test")]
- public HttpResponseMessage Get()
- {
- return Request.CreateResponse(HttpStatusCode.OK, "hello from a secured resource!");
- }
- }
Step 6
Now check the authorization on the basis of the token, so in the Program class validate it.
- static void Main()
- {
- string baseAddress = "http://localhost:9000/";
- // Start OWIN host
- using (WebApp.Start<Startup>(url: baseAddress))
- {
- var client = new HttpClient();
- var response = client.GetAsync(baseAddress + "test").Result;
- Console.WriteLine(response);
- Console.WriteLine();
- var authorizationHeader = Convert.ToBase64String(Encoding.UTF8.GetBytes("rajeev:secretKey"));
- client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authorizationHeader);
- var form = new Dictionary<string, string>
- {
- {"grant_type", "password"},
- {"username", "rranjan"},
- {"password", "password@123"},
- };
- var tokenResponse = client.PostAsync(baseAddress + "accesstoken", new FormUrlEncodedContent(form)).Result;
- var token = tokenResponse.Content.ReadAsAsync<Token>(new[] { new JsonMediaTypeFormatter() }).Result;
- Console.WriteLine("Token issued is: {0}", token.AccessToken);
- Console.WriteLine();
- client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
- var authorizedResponse = client.GetAsync(baseAddress + "test").Result;
- Console.WriteLine(authorizedResponse);
- Console.WriteLine(authorizedResponse.Content.ReadAsStringAsync().Result);
- }
- Console.ReadLine();
- }
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.