各种语言实现的oauth认证: http://oauth.net/code/

上一篇文章介绍了如何使用基本的http认证来实现asp.net web api的跨平台安全认证。 这里说明一个如何使用oauth实现的认证。oauth大家可能不陌生。那么这里需要注意的是我们使用的是.net平台一个比较好的开源oauth库。 DOTNETOPENAUTH。

就像上图所示,我们需要一个ISSSUE Server来给我们一个token,然后再去资源服务器请求资源,也就是Web API Server。

首先在oAuthIssuer服务端我们需要实现一个DotNetOpenAuth的接口:IAuthorizationServer

对接口的实现:

public class OAuth2Issuer : IAuthorizationServer
{
private readonly IssuerConfiguration _configuration; public OAuth2Issuer(IssuerConfiguration configuration)
{
if (configuration == null) throw new ArgumentNullException("configuration");
_configuration = configuration;
} public RSACryptoServiceProvider AccessTokenSigningKey
{
get
{
return (RSACryptoServiceProvider)_configuration.SigningCertificate.PrivateKey;
}
} public DotNetOpenAuth.Messaging.Bindings.ICryptoKeyStore CryptoKeyStore
{
get { throw new NotImplementedException(); }
} public TimeSpan GetAccessTokenLifetime(DotNetOpenAuth.OAuth2.Messages.IAccessTokenRequest accessTokenRequestMessage)
{
return _configuration.TokenLifetime;
} public IClientDescription GetClient(string clientIdentifier)
{
const string secretPassword = "test1243";
return new ClientDescription(secretPassword, new Uri("http://localhost/"), ClientType.Confidential);
} public RSACryptoServiceProvider GetResourceServerEncryptionKey(DotNetOpenAuth.OAuth2.Messages.IAccessTokenRequest accessTokenRequestMessage)
{
return (RSACryptoServiceProvider)_configuration.EncryptionCertificate.PublicKey.Key; } public bool IsAuthorizationValid(DotNetOpenAuth.OAuth2.ChannelElements.IAuthorizationDescription authorization)
{ //claims added to the token
authorization.Scope.Add("adminstrator");
authorization.Scope.Add("poweruser"); return true;
} public bool IsResourceOwnerCredentialValid(string userName, string password)
{
return true;
} public DotNetOpenAuth.Messaging.Bindings.INonceStore VerificationCodeNonceStore
{
get
{
throw new NotImplementedException();
}
}
}

在 Web API Server端,我们需要使用Http Message Handler来获取httprequest信息;并进行是否有授权认证。

 public class OAuth2Handler : DelegatingHandler
{
private readonly ResourceServerConfiguration _configuration; public OAuth2Handler(ResourceServerConfiguration configuration)
{
if (configuration == null) throw new ArgumentNullException("configuration");
_configuration = configuration;
} protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
HttpContextBase httpContext;
string userName;
HashSet<string> scope; if (!request.TryGetHttpContext(out httpContext))
throw new InvalidOperationException("HttpContext must not be null."); var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(
(RSACryptoServiceProvider)_configuration.IssuerSigningCertificate.PublicKey.Key,
(RSACryptoServiceProvider)_configuration.EncryptionVerificationCertificate.PrivateKey)); var error = resourceServer.VerifyAccess(httpContext.Request, out userName, out scope); if (error != null)
return Task<HttpResponseMessage>.Factory.StartNew(error.ToHttpResponseMessage); var identity = new ClaimsIdentity(scope.Select(s => new Claim(s, s)));
if (!string.IsNullOrEmpty(userName))
identity.Claims.Add(new Claim(ClaimTypes.Name, userName)); httpContext.User = ClaimsPrincipal.CreateFromIdentity(identity);
Thread.CurrentPrincipal = httpContext.User; return base.SendAsync(request, cancellationToken);
} }

这里的ResourceServerConfiguration 我们是使用加密证书的。

客户端调用代码:

调用API获取数据之前需要从IssueServer获取Token。

GetAccessToken:

看一下Token信息:

{"access_token":"gAAAAIoUBVBrZ5jAxe5XeTgnJ8mGwwKsCReknueg4gLGlDQ77lR1yPfxt0yNfWLCBT7hxnHjRjuEwDTJ3J1YAnqML4MIgQg8A2cz2bs0EnxvCMfKnayKEesRM-lxLTFbWMpSxe2Xvjm61IbaXjrMkYDRMnV4Do8-7132tiOLIv02WOGlJAEAAIAAAACJ8F3SsE6cTI1XsioW_xOxHeESDzG16y01Gxm3HikYFUC3XIdekpPw0yMB4tavPmUj-kRyC1halbUX7JKf-Dihm6Ou5mexe9lcYTr9or_kH7WcDN5ZCryUK3OaecvwwjQVr5o9XD2ZyZSNDCNhVRFc5ypvP85zZCBW1KJkP3OTCV4AkMN-ROvgI8jxutYdsLLN-YbB7Ot5iypzWWbW0QxiwOzMEqG9nVtPwnIWOUMOvW5KbiELELhgjap60mwHzGrHG4TtA4jrNy8S9zjixO_q-FrgpAuC06CkSH-R4w9yPCLLDc9m3UoAnknFjd4PUbWLxCvlBpEK2sg03ENa0EOKzc2O5fEic9P-BiYt6afMwTgLkJlGBBjmCBpGZMkfLTw","token_type":"bearer","expires_in":"300","scope":"http:\/\/localhost\/ adminstrator poweruser"}

客户端调用:

http://www.cnblogs.com/n-pei/archive/2012/05/29/2524673.html

Asp.Net MVC 4 Web API 中的安全认证-使用OAuth的更多相关文章

  1. ASP.NET MVC和Web API中的Angular2 - 第2部分

    下载源码 内容 第1部分:Visual Studio 2017中的Angular2设置,基本CRUD应用程序,第三方模态弹出控件 第2部分:使用Angular2管道进行过滤/搜索,全局错误处理,调试客 ...

  2. ASP.NET MVC和Web API中的Angular2 - 第1部分

    下载源码 - 903.5 KB 内容 第1部分:Visual Studio 2017中的Angular2设置,基本CRUD应用程序,第三方模态弹出控件 第2部分:使用Angular2管道进行过滤/搜索 ...

  3. ABP示例程序-使用AngularJs,ASP.NET MVC,Web API和EntityFramework创建N层的单页面Web应用

    本片文章翻译自ABP在CodeProject上的一个简单示例程序,网站上的程序是用ABP之前的版本创建的,模板创建界面及工程文档有所改变,本文基于最新的模板创建.通过这个简单的示例可以对ABP有个更深 ...

  4. [Asp.Net] MVC 和Web API Action 获取参数的区别

    Asp.net MVC 和web api 的action 在获取从前台传入的数据是有很大不同 前台使用ajax的方式向后台发起post的请求 Content-Type:application/json ...

  5. vs 2013下自定义ASP.net MVC 5/Web API 2 模板(T4 视图模板/控制器模板)

    vs 2013下自定义ASP.net MVC 5/Web API 2  模板(T4 视图模板/控制器模板): Customizing ASP.NET MVC 5/Web API 2 Scaffoldi ...

  6. ASP.NET MVC+Knockout+Web API+SignalR

    架构设计(ASP.NET MVC+Knockout+Web API+SignalR) 架构设计(ASP.NET MVC+Knockout+Web API+SignalR) 2014-01-16 18: ...

  7. Visual Studio 2013 Preview - ASP.NET, MVC 5, Web API 2新功能搶先看

    Visual Studio 2013 Preview - ASP.NET, MVC 5, Web API 2新功能搶先看 來自TechEd North America 2013的第一手消息 以下資訊均 ...

  8. [Angularjs]asp.net mvc+angularjs+web api单页应用

    写在前面 最近的工作一直在弄一些h5的单页应用,然后嵌入到app的webview中.之前一直在用angularjs+html+ashx的一套东西.实在是玩腻了.然后就尝试通过asp.net mvc的方 ...

  9. Asp.net MVC使用FormsAuthentication,MVC和WEB API可以共享身份认证 (转载)

    在实际的项目应用中,很多时候都需要保证数据的安全和可靠,如何来保证数据的安全呢?做法有很多,最常见的就是进行身份验证.验证通过,根据验证过的身份给与对应访问权限.同在Web Api中如何实现身份认证呢 ...

随机推荐

  1. Android Service使用拾遗[阿里工程师分享]

    Service作为android的四大组件之一常用来帮助我们完成一些需要放在后台处理的任务,通过startService和bindService两种方式被调用.因为Service也是在主线程中运行的, ...

  2. iOS开发Facebook POP动效库使用教程

    如果说Origami这款动效原型工具是Facebook Paper的幕后功臣,那么POP便是Origami的地基.感谢Facebook开源了POP动效库,让人人都能制作出华丽的动效.我们只需5步,便能 ...

  3. IOC基础

    Ioc-Inversion of Control,即"控制反转",不是什么技术,而是一种设计思想.在Java开发中,Ioc意味着将你设计好的对象交给容器控制,而不是传统的在你的对象 ...

  4. Java 读取txt文件,读取结果保存到数据库

    需求:有一个很大的txt文件(1,000,000条数据),从txt中读取有用数据库后保存到Oracle数据库中 利用Java实现: 1.加载文件后一行一行读取 2.数据库连接后按行插入到数据库 pac ...

  5. C#获取HTML文件指定DIV内容

    最近自己找了一个开源的博客网站,放到阿里云上,方便自己发布博客. 我一般把文章发布到博客园和QQ空间,家了这个网站后又要多发布一次,为了省事就做了一个从博客园读取文章的功能: 输入链接URL地址点击提 ...

  6. mongo学习笔记(五):分片

    分片  人脸:       代表客户端,客户端肯定说,你数据库分片不分片跟我没关系,我叫你干啥就干啥,没什么好商量的. mongos: 首先我们要了解”片键“的概念,也就是说拆分集合的依据是什么?按照 ...

  7. Eclipse++Xdebug开发php环境配置

    一.php环境配置: 本次使用了appserv 2.5.10集成安装包.具体版本如下,安装后php版本是5.2.6 vc6,apache版本2.2 安装完成后,php配置文件在c:\windows目录 ...

  8. easyui-validatebox 验证两次密码是否输入一致

    验证两次密码是否输入一致 $.extend($.fn.validatebox.defaults.rules, {        /*必须和某个字段相等*/        equalTo: { vali ...

  9. gdb调试常用命令

    gdb 调试常用命令 gcc -g mian.c -o main.out -o (定制生成的可执行文件的名称,缺省时为a.out) -g 使gdb可调试,在编译的时候,产生调试信息 gdb main. ...

  10. Hadoop 文件的数量怎么比block的数量多?

    Total files:    23 Total symlinks:        0 Total blocks (validated):    22 (avg. block size 117723 ...