OK, Service创建完成了,你可以把它部署到ACS或者是其他Server。下面我们来创建一个安全模块来保护这个Service,这个模块有两个类,一个为SWTModule.cs,他用于设置SWT类型令牌的信任关系,这里需要你吧刚刚在Azure ACS管理页面上设置信息写入了,例如ACS的命名空间,你的密码和acs路径。他是继承与IHttpModule接口的,也就是说在调用Service之前,你需要通过这个HttpModule的验证。另外一个类时TokenValidator,如字面意思,这个类用来检查你的Token的正确性,包括检查你的Token的名字,信任的key,过期时间,SHA-256加密等等. 这两个类是验证功能的核心部分。
SWTMoudle.cs:
- class SWTMoudle : IHttpModule
- {
- string serviceNamespace = "<Your ACS namespace>";
- string acsHostName = "accesscontrol.windows.net";
- // Certificate and keys
- string trustedTokenPolicyKey = "<Your Signing certificate symmetric key>";
- // Service Realm
- string trustedAudience = "<Your ACS service path>";
- void IHttpModule.Dispose()
- {
- }
- void IHttpModule.Init(HttpApplication context)
- {
- context.BeginRequest += new EventHandler(context_BeginRequest);
- }
- void context_BeginRequest(object sender, EventArgs e)
- {
- if (HttpContext.Current.Request.Url.AbsolutePath.EndsWith(".svc"))
- {
- // Get the authorization header
- string headerValue = HttpContext.Current.Request.Headers.Get("Authorization");
- // Check that a value is there
- if (string.IsNullOrEmpty(headerValue))
- {
- throw new ApplicationException("unauthorized");
- }
- // Check that it starts with 'WRAP'
- if (!headerValue.StartsWith("WRAP "))
- {
- throw new ApplicationException("unauthorized");
- }
- string[] nameValuePair = headerValue.Substring("WRAP ".Length).Split(new char[] { '=' }, 2);
- if (nameValuePair.Length != 2 ||
- nameValuePair[0] != "access_token" ||
- !nameValuePair[1].StartsWith("\"") ||
- !nameValuePair[1].EndsWith("\""))
- {
- throw new ApplicationException("unauthorized");
- }
- // Trim off the leading and trailing double-quotes
- string token = nameValuePair[1].Substring(1, nameValuePair[1].Length - 2);
- // Create a token validate
- TokenValidator validator = new TokenValidator(
- this.acsHostName,
- this.serviceNamespace,
- this.trustedAudience,
- this.trustedTokenPolicyKey);
- // Validate the token
- if (!validator.Validate(token))
- {
- throw new ApplicationException("unauthorized");
- }
- }
- }
- }
TokenValidator.cs
- public class TokenValidator
- {
- private string issuerLabel = "Issuer";
- private string expiresLabel = "ExpiresOn";
- private string audienceLabel = "Audience";
- private string hmacSHA256Label = "HMACSHA256";
- private string acsHostName;
- private string trustedSigningKey;
- private string trustedTokenIssuer;
- private string trustedAudienceValue;
- /// <summary>
- /// Token validate constructor method.
- /// </summary>
- /// <param name="acsHostName"></param>
- /// <param name="serviceNamespace"></param>
- /// <param name="trustedAudienceValue"></param>
- /// <param name="trustedSigningKey"></param>
- public TokenValidator(string acsHostName, string serviceNamespace, string trustedAudienceValue, string trustedSigningKey)
- {
- this.trustedSigningKey = trustedSigningKey;
- this.trustedTokenIssuer = String.Format("https://{0}.{1}/",
- serviceNamespace.ToLowerInvariant(),
- acsHostName.ToLowerInvariant());
- this.trustedAudienceValue = trustedAudienceValue;
- }
- public bool Validate(string token)
- {
- if (!this.IsHMACValid(token, Convert.FromBase64String(this.trustedSigningKey)))
- {
- return false;
- }
- if (this.IsExpired(token))
- {
- return false;
- }
- if (!this.IsIssuerTrusted(token))
- {
- return false;
- }
- if (!this.IsAudienceTrusted(token))
- {
- return false;
- }
- return true;
- }
- public Dictionary<string, string> GetNameValues(string token)
- {
- if (string.IsNullOrEmpty(token))
- {
- throw new ArgumentException();
- }
- return
- token
- .Split('&')
- .Aggregate(
- new Dictionary<string, string>(),
- (dict, rawNameValue) =>
- {
- if (rawNameValue == string.Empty)
- {
- return dict;
- }
- string[] nameValue = rawNameValue.Split('=');
- if (nameValue.Length != 2)
- {
- throw new ArgumentException("Invalid formEncodedstring - contains a name/value pair missing an = character");
- }
- if (dict.ContainsKey(nameValue[0]) == true)
- {
- throw new ArgumentException("Repeated name/value pair in form");
- }
- dict.Add(HttpUtility.UrlDecode(nameValue[0]), HttpUtility.UrlDecode(nameValue[1]));
- return dict;
- });
- }
- private static ulong GenerateTimeStamp()
- {
- // Default implementation of epoch time
- TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
- return Convert.ToUInt64(ts.TotalSeconds);
- }
- private bool IsAudienceTrusted(string token)
- {
- Dictionary<string, string> tokenValues = this.GetNameValues(token);
- string audienceValue;
- tokenValues.TryGetValue(this.audienceLabel, out audienceValue);
- if (!string.IsNullOrEmpty(audienceValue))
- {
- if (audienceValue.Equals(this.trustedAudienceValue, StringComparison.Ordinal))
- {
- return true;
- }
- }
- return false;
- }
- private bool IsIssuerTrusted(string token)
- {
- Dictionary<string, string> tokenValues = this.GetNameValues(token);
- string issuerName;
- tokenValues.TryGetValue(this.issuerLabel, out issuerName);
- if (!string.IsNullOrEmpty(issuerName))
- {
- if (issuerName.Equals(this.trustedTokenIssuer))
- {
- return true;
- }
- }
- return false;
- }
- private bool IsHMACValid(string swt, byte[] sha256HMACKey)
- {
- string[] swtWithSignature = swt.Split(new string[] { "&" + this.hmacSHA256Label + "=" }, StringSplitOptions.None);
- if ((swtWithSignature == null) || (swtWithSignature.Length != 2))
- {
- return false;
- }
- HMACSHA256 hmac = new HMACSHA256(sha256HMACKey);
- byte[] locallyGeneratedSignatureInBytes = hmac.ComputeHash(Encoding.ASCII.GetBytes(swtWithSignature[0]));
- string locallyGeneratedSignature = HttpUtility.UrlEncode(Convert.ToBase64String(locallyGeneratedSignatureInBytes));
- return locallyGeneratedSignature == swtWithSignature[1];
- }
- private bool IsExpired(string swt)
- {
- try
- {
- Dictionary<string, string> nameValues = this.GetNameValues(swt);
- string expiresOnValue = nameValues[this.expiresLabel];
- ulong expiresOn = Convert.ToUInt64(expiresOnValue);
- ulong currentTime = Convert.ToUInt64(GenerateTimeStamp());
- if (currentTime > expiresOn)
- {
- return true;
- }
- return false;
- }
- catch (KeyNotFoundException)
- {
- throw new ArgumentException();
- }
- }
- }
