2016-08-22 92 views
0

我有一個signalR服務器,需要驗證客戶端從Azure AD獲取的OAuth令牌。我想在AuthorizeHubConnection方法中做到這一點。 我想這http://geekswithblogs.net/shaunxu/archive/2014/05/27.aspx基本上做到這一點: 變種d在SignalR中驗證OAuth/AAD令牌

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); 

    ... 

這裏的問題是,它提出了從卡塔納項目複製類:https://katanaproject.codeplex.com/SourceControl/latest#src/Microsoft.Owin.Security.ActiveDirectory/WsFedCachingSecurityTokenProvider.cs 。 這看起來非常難看。另一個問題是,我不知道租戶ID,我在任何地方都找不到令牌。所以,即使這樣做,我會離開一步。

包裝它:我想找到一種方法來驗證與SignalR的AzureAD令牌。它在開始時看起來很簡單。有沒有一個簡單的方法呢?

回答

0

很簡單:

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