在SignalR中验证OAuth / AAD令牌

时间:2016-08-22 17:17:27

标签: c# oauth signalr jwt adal

我有一个signalR服务器,我需要验证客户端将从Azure AD获取的OAuth令牌。我想在AuthorizeHubConnection方法中执行此操作。 我尝试了这个http://geekswithblogs.net/shaunxu/archive/2014/05/27.aspx基本上这样做: var d

dataProtectionProvider = new DpapiDataProtectionProvider();
var secureDataFormat = new TicketDataFormat(dataProtectionProvider.Create());
// authenticate by using bearer token in query string
var token = request.QueryString.Get(WebApiConfig.AuthenticationType);
var ticket = secureDataFormat.Unprotect(token);

这将始终在故障单中返回null。

经过一番搜索,我发现了这篇文章:http://ronaldwildenberg.com/signalr-hub-authentication-with-adal-js-part-2/

这是它的作用:

public class JwtTokenAuthorizeAttribute : AuthorizeAttribute  
{
  // Location of the federation metadata document for our tenant.
  private const string SecurityTokenServiceAddressFormat =
      "https://login.windows.net/{0}/federationmetadata/2007-06/federationmetadata.xml";

  private static readonly string Tenant = "yourtenant.onmicrosoft.com";
  private static readonly string ClientId = "12345678-ABCD-EFAB-1234-ABCDEF123456";

  private static readonly string MetadataEndpoint = string.Format(
      CultureInfo.InvariantCulture, SecurityTokenServiceAddressFormat, Tenant);

  private static readonly IIssuerSecurityTokenProvider CachingSecurityTokenProvider =
      new WsFedCachingSecurityTokenProvider(
          metadataEndpoint: MetadataEndpoint,
          backchannelCertificateValidator: null,
          backchannelTimeout: TimeSpan.FromMinutes(1),
          backchannelHttpHandler: null);

  public override bool AuthorizeHubConnection(
      HubDescriptor hubDescriptor, IRequest request)
  {
    // Extract JWT token from query string (which we already did).
    ...  

    // Validate JWT token.
    var tokenValidationParameters =
        new TokenValidationParameters { ValidAudience = ClientId };
    var jwtFormat =
        new JwtFormat(tokenValidationParameters, CachingSecurityTokenProvider);
    var authenticationTicket = jwtFormat.Unprotect(userJwtToken);

    ...

这个问题是它建议从Katana项目中复制类:https://katanaproject.codeplex.com/SourceControl/latest#src/Microsoft.Owin.Security.ActiveDirectory/WsFedCachingSecurityTokenProvider.cs。 这看起来非常难看。另一个问题是,我不知道租户ID,我无法通过令牌在任何地方找到它。所以,即使这样做,我也会有一步之遥。

包装起来:我想找到一种方法来使用SignalR验证AzureAD令牌。一开始看起来很简单。对此有简单的方法吗?

1 个答案:

答案 0 :(得分:0)

很简单:

JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
tokenHandler.ValidateToken(token, authTokenValidationParameters, out validatedToken);