你好,游客 登录 注册 搜索
背景:
阅读新闻

使用OAuth方式保护你的WCF Service(通过Azure ACS)

[日期:2012-07-27] 来源:Linux社区  作者:aa466564931 [字体:大 中 小]

OK, Service创建完成了,你可以把它部署到ACS或者是其他Server。下面我们来创建一个安全模块来保护这个Service,这个模块有两个类,一个为SWTModule.cs,他用于设置SWT类型令牌的信任关系,这里需要你吧刚刚在Azure ACS管理页面上设置信息写入了,例如ACS的命名空间,你的密码和acs路径。他是继承与IHttpModule接口的,也就是说在调用Service之前,你需要通过这个HttpModule的验证。另外一个类时TokenValidator,如字面意思,这个类用来检查你的Token的正确性,包括检查你的Token的名字,信任的key,过期时间,SHA-256加密等等. 这两个类是验证功能的核心部分。

SWTMoudle.cs:

  1. class SWTMoudle : IHttpModule  
  2. {  
  3.     string serviceNamespace = "<Your ACS namespace>";  
  4.     string acsHostName = "accesscontrol.windows.net";  
  5.     // Certificate and keys   
  6.     string trustedTokenPolicyKey = "<Your Signing certificate symmetric key>";  
  7.     // Service Realm   
  8.     string trustedAudience = "<Your ACS service path>";  
  9.   
  10.   
  11.     void IHttpModule.Dispose()  
  12.     {  
  13.   
  14.     }  
  15.   
  16.     void IHttpModule.Init(HttpApplication context)  
  17.     {  
  18.         context.BeginRequest += new EventHandler(context_BeginRequest);  
  19.     }  
  20.   
  21.     void context_BeginRequest(object sender, EventArgs e)  
  22.     {  
  23.         if (HttpContext.Current.Request.Url.AbsolutePath.EndsWith(".svc"))  
  24.         {  
  25.             // Get the authorization header   
  26.             string headerValue = HttpContext.Current.Request.Headers.Get("Authorization");  
  27.   
  28.             // Check that a value is there   
  29.             if (string.IsNullOrEmpty(headerValue))  
  30.             {  
  31.                 throw new ApplicationException("unauthorized");  
  32.             }  
  33.   
  34.             // Check that it starts with 'WRAP'   
  35.             if (!headerValue.StartsWith("WRAP "))  
  36.             {  
  37.                 throw new ApplicationException("unauthorized");  
  38.             }  
  39.   
  40.             string[] nameValuePair = headerValue.Substring("WRAP ".Length).Split(new char[] { '=' }, 2);  
  41.   
  42.             if (nameValuePair.Length != 2 ||  
  43.                 nameValuePair[0] != "access_token" ||  
  44.                 !nameValuePair[1].StartsWith("\"") ||  
  45.                 !nameValuePair[1].EndsWith("\""))  
  46.             {  
  47.                 throw new ApplicationException("unauthorized");  
  48.             }  
  49.   
  50.             // Trim off the leading and trailing double-quotes   
  51.             string token = nameValuePair[1].Substring(1, nameValuePair[1].Length - 2);  
  52.   
  53.             // Create a token validate   
  54.             TokenValidator validator = new TokenValidator(  
  55.                 this.acsHostName,  
  56.                 this.serviceNamespace,  
  57.                 this.trustedAudience,  
  58.                 this.trustedTokenPolicyKey);  
  59.   
  60.             // Validate the token   
  61.             if (!validator.Validate(token))  
  62.             {  
  63.                 throw new ApplicationException("unauthorized");  
  64.             }  
  65.         }  
  66.     }  
  67.   
  68. }  

TokenValidator.cs

  1. public class TokenValidator  
  2. {  
  3.     private string issuerLabel = "Issuer";  
  4.     private string expiresLabel = "ExpiresOn";  
  5.     private string audienceLabel = "Audience";  
  6.     private string hmacSHA256Label = "HMACSHA256";  
  7.   
  8.     private string acsHostName;  
  9.   
  10.     private string trustedSigningKey;  
  11.     private string trustedTokenIssuer;  
  12.     private string trustedAudienceValue;  
  13.   
  14.     /// <summary>   
  15.     /// Token validate constructor method.   
  16.     /// </summary>   
  17.     /// <param name="acsHostName"></param>   
  18.     /// <param name="serviceNamespace"></param>   
  19.     /// <param name="trustedAudienceValue"></param>   
  20.     /// <param name="trustedSigningKey"></param>   
  21.     public TokenValidator(string acsHostName, string serviceNamespace, string trustedAudienceValue, string trustedSigningKey)  
  22.     {  
  23.         this.trustedSigningKey = trustedSigningKey;  
  24.         this.trustedTokenIssuer = String.Format("https://{0}.{1}/",  
  25.             serviceNamespace.ToLowerInvariant(),  
  26.             acsHostName.ToLowerInvariant());  
  27.   
  28.         this.trustedAudienceValue = trustedAudienceValue;  
  29.     }  
  30.   
  31.     public bool Validate(string token)  
  32.     {  
  33.         if (!this.IsHMACValid(token, Convert.FromBase64String(this.trustedSigningKey)))  
  34.         {  
  35.             return false;  
  36.         }  
  37.   
  38.         if (this.IsExpired(token))  
  39.         {  
  40.             return false;  
  41.         }  
  42.   
  43.         if (!this.IsIssuerTrusted(token))  
  44.         {  
  45.             return false;  
  46.         }  
  47.   
  48.         if (!this.IsAudienceTrusted(token))  
  49.         {  
  50.             return false;  
  51.         }  
  52.   
  53.         return true;  
  54.     }  
  55.   
  56.     public Dictionary<string, string> GetNameValues(string token)  
  57.     {  
  58.         if (string.IsNullOrEmpty(token))  
  59.         {  
  60.             throw new ArgumentException();  
  61.         }  
  62.   
  63.         return  
  64.             token  
  65.             .Split('&')  
  66.             .Aggregate(  
  67.             new Dictionary<string, string>(),  
  68.             (dict, rawNameValue) =>  
  69.             {  
  70.                 if (rawNameValue == string.Empty)  
  71.                 {  
  72.                     return dict;  
  73.                 }  
  74.   
  75.                 string[] nameValue = rawNameValue.Split('=');  
  76.   
  77.                 if (nameValue.Length != 2)  
  78.                 {  
  79.                     throw new ArgumentException("Invalid formEncodedstring - contains a name/value pair missing an = character");  
  80.                 }  
  81.   
  82.                 if (dict.ContainsKey(nameValue[0]) == true)  
  83.                 {  
  84.                     throw new ArgumentException("Repeated name/value pair in form");  
  85.                 }  
  86.   
  87.                 dict.Add(HttpUtility.UrlDecode(nameValue[0]), HttpUtility.UrlDecode(nameValue[1]));  
  88.                 return dict;  
  89.             });  
  90.     }  
  91.   
  92.     private static ulong GenerateTimeStamp()  
  93.     {  
  94.         // Default implementation of epoch time   
  95.         TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);  
  96.         return Convert.ToUInt64(ts.TotalSeconds);  
  97.     }  
  98.   
  99.     private bool IsAudienceTrusted(string token)  
  100.     {  
  101.         Dictionary<string, string> tokenValues = this.GetNameValues(token);  
  102.   
  103.         string audienceValue;  
  104.   
  105.         tokenValues.TryGetValue(this.audienceLabel, out audienceValue);  
  106.   
  107.         if (!string.IsNullOrEmpty(audienceValue))  
  108.         {  
  109.             if (audienceValue.Equals(this.trustedAudienceValue, StringComparison.Ordinal))  
  110.             {  
  111.                 return true;  
  112.             }  
  113.         }  
  114.   
  115.         return false;  
  116.     }  
  117.   
  118.     private bool IsIssuerTrusted(string token)  
  119.     {  
  120.         Dictionary<string, string> tokenValues = this.GetNameValues(token);  
  121.   
  122.         string issuerName;  
  123.   
  124.         tokenValues.TryGetValue(this.issuerLabel, out issuerName);  
  125.   
  126.         if (!string.IsNullOrEmpty(issuerName))  
  127.         {  
  128.             if (issuerName.Equals(this.trustedTokenIssuer))  
  129.             {  
  130.                 return true;  
  131.             }  
  132.         }  
  133.   
  134.         return false;  
  135.     }  
  136.   
  137.     private bool IsHMACValid(string swt, byte[] sha256HMACKey)  
  138.     {  
  139.         string[] swtWithSignature = swt.Split(new string[] { "&" + this.hmacSHA256Label + "=" }, StringSplitOptions.None);  
  140.   
  141.         if ((swtWithSignature == null) || (swtWithSignature.Length != 2))  
  142.         {  
  143.             return false;  
  144.         }  
  145.   
  146.         HMACSHA256 hmac = new HMACSHA256(sha256HMACKey);  
  147.   
  148.         byte[] locallyGeneratedSignatureInBytes = hmac.ComputeHash(Encoding.ASCII.GetBytes(swtWithSignature[0]));  
  149.   
  150.         string locallyGeneratedSignature = HttpUtility.UrlEncode(Convert.ToBase64String(locallyGeneratedSignatureInBytes));  
  151.   
  152.         return locallyGeneratedSignature == swtWithSignature[1];  
  153.     }  
  154.   
  155.     private bool IsExpired(string swt)  
  156.     {  
  157.         try  
  158.         {  
  159.             Dictionary<string, string> nameValues = this.GetNameValues(swt);  
  160.             string expiresOnValue = nameValues[this.expiresLabel];  
  161.             ulong expiresOn = Convert.ToUInt64(expiresOnValue);  
  162.             ulong currentTime = Convert.ToUInt64(GenerateTimeStamp());  
  163.   
  164.             if (currentTime > expiresOn)  
  165.             {  
  166.                 return true;  
  167.             }  
  168.   
  169.             return false;  
  170.         }  
  171.         catch (KeyNotFoundException)  
  172.         {  
  173.             throw new ArgumentException();  
  174.         }  
  175.     }  
  176.   
  177. }  
linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款