在 SignalR 中验证 OAuth/AAD 令牌

Validate OAuth/AAD token in SignalR

我有一个 signalR 服务器,我需要验证客户端将从 Azure AD 获得的 OAuth 令牌。我想在 AuthorizeHubConnection 方法中进行。 我试过这个 http://geekswithblogs.net/shaunxu/archive/2014/05/27.aspx 基本上是这样做的: 变量 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);

这将在工单中始终 return 为空。

经过一番搜索,我发现了这篇文章: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 令牌的方法。一开始看起来很简单。有没有简单的方法?

很简单:

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