各种语言实现的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. JAVA基础学习day15--集合二 TreeSet和泛型

    一.TreeSet 1.1.TreeSet Set:hashSet:数据结构是哈希表.线程是非同步的.        保证元素唯一性的原理:判断元素的HashCode值是否相同.         如果 ...

  2. MacOs终端忽略大小写

    使用MacOs的终端时,唯一让人感觉不爽的就是Tab补全是区分大小的,所以查了资料就把这个问题搞定了.在用户目录下创建 .inputrc 文件,内容为以下三行代码,保存后重启终端再次输入文件名Tab补 ...

  3. NSArray数字和排序

    1.数字 int main(int argc, const char * argv[]) { @autoreleasepool { //添加空白 [NSNull null] // NSArray *a ...

  4. Objective-C 代码规范(Code Style)

    我们写出来的代码会给很多人看,为了使代码清晰简洁,方便阅读理解,都会统一遵从一定的代码规范,Objective-C同样如此. 主要参考规范: 1.Google Objective-C Style Gu ...

  5. iOS之UI--主流框架的搭建--仿制QQ的UI框架

    使用XCode搭建多个控制器界面,一般在实际开发中建议超过四个控制器界面使用纯代码. 下面的实例其实已经超过了四个,总结详细步骤的目的,主要是更熟悉XCode的StoryBoard使用细节. 先直接上 ...

  6. 数据仓库建模与ETL实践技巧

    数据分析系统的总体架构分为四个部分 —— 源系统.数据仓库.多维数据库.客户端(图一:pic1.bmp) 其中,数据仓库(DW)起到了数据大集中的作用.通过数据抽取,把数据从源系统源源不断地抽取出来, ...

  7. Effective Java 76 Write readObject methods defensively

    Principle readObject method is effectively another public constructor, and it demands all of the sam ...

  8. Greenplum源码编译安装(单机及集群模式)完全攻略

    公司有个项目需要安装greenplum数据库,让我这个gp小白很是受伤,在网上各种搜,结果找到的都是TMD坑货帖子,但是经过4日苦战,总算是把greenplum的安装弄了个明白,单机及集群模式都部署成 ...

  9. linux设置tomcat开机启动

    [root@iZ94j7ahvuvZ ~]# cd /etc/rc.d/ [root@iZ94j7ahvuvZ rc.d]# cat rc.local #!/bin/sh # # This scrip ...

  10. 小结getBytes()默认编码导致的xml字符串中出现乱码

    遇到乱码第一印象想到的是如何统一编码,很少注意到这期间穿插的某些过程也是一大隐患.. sae上部署了一个spring写的微信小程序,手机总关注测试号点击菜单得到的文本消息却是乱码.. 聚焦发送消息的部 ...