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:
- 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.
Token Based Authentication in Web API 2的更多相关文章
- Claims Based Authentication and Token Based Authentication和WIF
基于声明的认证方式,其最大特性是可传递(一方面是由授信的Issuer,即claims持有方,发送到你的应用上,注意信任是单向的.例如QQ集成登录,登录成功后,QQ会向你的应用发送claims.另一方面 ...
- [转] 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/ ...
- 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 ...
- Dynamics CRM模拟OAuth请求获得Token后在外部调用Web API
关注本人微信和易信公众号: 微软动态CRM专家罗勇 ,回复233或者20161104可方便获取本文,同时可以在第一间得到我发布的最新的博文信息,follow me!我的网站是 www.luoyong. ...
- Asp.Net MVC webAPI Token based authentication
1. 需要安装的nuget <package id="Microsoft.AspNet.Identity.Core" version="2.2.1" ta ...
- 基于JWT(Json Web Token)的ASP.NET Web API授权方式
token应用流程 初次登录:用户初次登录,输入用户名密码 密码验证:服务器从数据库取出用户名和密码进行验证 生成JWT:服务器端验证通过,根据从数据库返回的信息,以及预设规则,生成JWT 返还JWT ...
- Token Based Authentication -- Implementation Demonstration
https://www.w3.org/2001/sw/Europe/events/foaf-galway/papers/fp/token_based_authentication/
- 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 ...
- 在ASP.NET Web API 2中使用Owin基于Token令牌的身份验证
基于令牌的身份验证 基于令牌的身份验证主要区别于以前常用的常用的基于cookie的身份验证,基于cookie的身份验证在B/S架构中使用比较多,但是在Web Api中因其特殊性,基于cookie的身份 ...
随机推荐
- Git删除错误提交的commit
git reset --hard <commit_id> git push origin HEAD --force
- java中newInstance()和new()
在Java开发特别是数据库开发中,经常会用到Class.forName( )这个方法.通过查询Java Documentation我们会发现使用Class.forName( )静态方法的目的是为了动态 ...
- iCheck.js
一.iCheck:http://www.bootcss.com/p/icheck/ 1.选择一个颜色主题,网上有,有了一个肤色主题,然后就是把这个肤色主题的css文件复制到iCheck文件夹里面 2. ...
- css权重
1.行内样式,指的是html文档中定义的style <h1 style="color: #fff;">header</h1> 2.ID选择器 3.类,属性选 ...
- 如何实现桌面App图标可以动态显示消息数(类似手机上的QQ图标)?
手机上的APP , 像QQ和微信等都可以在图标上动态显示消息数(最大99) , 那么你有没有想过这些效果是如何实现的?桌面上开发的传统应用程序能否也实现类似的功能? 1 思路 桌面快捷方式的图标本质上 ...
- MixItUp:超炫!基于 CSS3 & jQuery 的过滤和排序插件
MixItUp 是一款轻量,但功能强大的 jQuery 插件,提供了对分类和有序内容的美丽的动画过滤和排序功能.特别适合用于作品集网站,画廊,图片博客以及任何的分类或有序内容. 它是如何工作的? Mi ...
- Eclipse 扩展点常量ID
eclipse 扩展点常量ID 列表如下: Name ID ------------------------------------------------- Category File ...
- Atitit.Atiposter 发帖机 信息发布器 v7 q516
Atitit.Atiposter 发帖机 信息发布器 v7 q516 V7 jetty 版本 基本访问改为web版. 这样发布调试 V1 初步实现sina csdn cnblogs V2 实现qz ...
- 盒图(boxplot)
最近在摆弄数据离散度的时候遇到一种图形,叫做盒图(boxplot).它对于显示数据的离散的分布情况效果不错. 盒图是在1977年由美国的统计学家约翰·图基(John Tukey)发明的.它由五个数值点 ...
- SharePoint 2013 为站点配置基于主机标头的双域名
SharePoint的应用中,经常需要配置双域名,为不同的认证方式提供访问入口,下面简单介绍下,如何以主机标头的方式为SharePoint配置双域名: 配置基于主机标头的双域名 1.原本可以访问的测试 ...