Asp.Net MVC 4 Web API 中的安全认证-使用OAuth

简介:

image

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

 

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

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

image

 

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

image

 

对接口的实现:

 

复制代码
复制代码
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 我们是使用加密证书的。

image

 

客户端调用代码:

image

 

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

GetAccessToken:

 

 

image

 

看一下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"}

image

 

客户端调用:

 

image

 

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

分类:  ASP.NET, WCF

本文转自左正博客园博客,原文链接:http://www.cnblogs.com/soundcode/p/3801469.html ,如需转载请自行联系原作者
相关文章
|
2月前
|
监控 前端开发 API
一款基于 .NET MVC 框架开发、功能全面的MES系统
一款基于 .NET MVC 框架开发、功能全面的MES系统
|
2月前
|
开发框架 .NET PHP
ASP.NET Web Pages - 添加 Razor 代码
ASP.NET Web Pages 使用 Razor 标记添加服务器端代码,支持 C# 和 Visual Basic。Razor 语法简洁易学,类似于 ASP 和 PHP。例如,在网页中加入 `@DateTime.Now` 可以实时显示当前时间。
|
2月前
|
开发框架 前端开发 JavaScript
ASP.NET Web Pages - 教程
ASP.NET Web Pages 是一种用于创建动态网页的开发模式,采用HTML、CSS、JavaScript 和服务器脚本。本教程聚焦于Web Pages,介绍如何使用Razor语法结合服务器端代码与前端技术,以及利用WebMatrix工具进行开发。适合初学者入门ASP.NET。
|
3月前
|
开发框架 .NET 程序员
驾驭Autofac,ASP.NET WebApi实现依赖注入详细步骤总结
Autofac 是一个轻量级的依赖注入框架,专门为 .NET 应用程序量身定做,它就像是你代码中的 "魔法师",用它来管理对象的生命周期,让你的代码更加模块化、易于测试和维护
104 4
驾驭Autofac,ASP.NET WebApi实现依赖注入详细步骤总结
|
4月前
|
开发框架 .NET API
Windows Forms应用程序中集成一个ASP.NET API服务
Windows Forms应用程序中集成一个ASP.NET API服务
124 9
|
5月前
|
开发框架 监控 前端开发
在 ASP.NET Core Web API 中使用操作筛选器统一处理通用操作
【9月更文挑战第27天】操作筛选器是ASP.NET Core MVC和Web API中的一种过滤器,可在操作方法执行前后运行代码,适用于日志记录、性能监控和验证等场景。通过实现`IActionFilter`接口的`OnActionExecuting`和`OnActionExecuted`方法,可以统一处理日志、验证及异常。创建并注册自定义筛选器类,能提升代码的可维护性和复用性。
|
5月前
|
开发框架 .NET 中间件
ASP.NET Core Web 开发浅谈
本文介绍ASP.NET Core,一个轻量级、开源的跨平台框架,专为构建高性能Web应用设计。通过简单步骤,你将学会创建首个Web应用。文章还深入探讨了路由配置、依赖注入及安全性配置等常见问题,并提供了实用示例代码以助于理解与避免错误,帮助开发者更好地掌握ASP.NET Core的核心概念。
141 3
|
5月前
|
开发框架 前端开发 .NET
VB.NET中如何利用ASP.NET进行Web开发
在VB.NET中利用ASP.NET进行Web开发是一个常见的做法,特别是在需要构建动态、交互式Web应用程序时。ASP.NET是一个由微软开发的开源Web应用程序框架,它允许开发者使用多种编程语言(包括VB.NET)来创建Web应用程序。
112 6
|
5月前
|
存储 开发框架 前端开发
ASP.NET MVC 迅速集成 SignalR
ASP.NET MVC 迅速集成 SignalR
114 0
|
5月前
|
开发框架 前端开发 JavaScript
ASP.NET MVC 教程
ASP.NET 是一个使用 HTML、CSS、JavaScript 和服务器脚本创建网页和网站的开发框架。
72 7

热门文章

最新文章