2017-08-29 130 views
0

我從我的應用獲取AzureAD的access_token和id_token,該應用使用帶有隱式流的OAuth2。這是我獲得令牌的示例URL:Asp.Net - Jwt承載身份驗證:無效簽名

https://login.microsoftonline.com/my_tenant_id/oauth2/v2.0/authorize?response_type=id_token+token&client_id=my_client_id&state=some_state&redirect_uri=http%3A%2F%2Flocalhost%3A4200%2Fsign-in&scope=openid%20https%3A%2F%2Fgraph.microsoft.com%2Fuser.read&nonce=some_nonce

範圍是openid https://grap.microsoft.com/user.read

response_type是id_token+token

我也有一個Asp.Net後端,我想保護。因此,我使用我的控制器的Authorize屬性,並在標題中發送標記,如下所示:「身份驗證:承載者THE_TOKEN」。

我在Startup.cs配置是這樣的:

app.UseJwtBearerAuthentication(new JwtBearerOptions 
{ 
    Authority = string.Format("https://login.microsoftonline.com/{0}/v2.0/", 
      "d67853c3-db96-4dac-a37b-f2bfb12b42d1"), 
    Audience = "8422b3fb-5612-4fdd-a90f-707d7218de57" 
}); 

從我已閱讀,訪問令牌應該用於此,而id_token不應該離開的前端。但是在我的情況下,後端的身份驗證只適用於id令牌。 access_token不能被簽字Bearer error="invalid_token", error_description="The signature is invalid"

查看jwt.io中的access_token,我看到令牌具有不同的受衆和發行者。例如具有的access_token這個

"aud": "https://graph.microsoft.com", 
"iss": "https://sts.windows.net/d67853c3-db96-4dac-a37b-f2bfb12b42d1/", 

而在ID標記有這個

"aud": "my_client_id", 
"iss": "https://login.microsoftonline.com/my_tenant_id/v2.0", 

所以,在我看來,該是的access_token莫名其妙的圖形API發出。如果有人能夠告訴我,我做錯了什麼或者我如何解決我的問題,會很高興。

編輯: 當我使用範圍openid profile時,它正如預期的那樣工作。但是由於Azure的變化,這個範圍不再有效,微軟指示我使用上面提到的範圍。

回答

1

如上所述,您請求的訪問令牌是Microsoft Graph。而id_token僅用於客戶端認證用戶而不是資源服務器。使用通過保護網絡API代碼

https://login.microsoftonline.com/common/oauth2/v2.0/authorize?response_type=token&client_id={client_id}&scope=api://{client_id}/access_as_user&redirect_uri={redirect_uri} 

在這裏:

要使用Azure的AD V2.0端點保護網絡API,我們可以獲取用於網絡API的訪問令牌像下面的請求Azure的AD V2.0端點:

public void ConfigureAuth(IAppBuilder app) 
{ 
    System.Diagnostics.Trace.TraceWarning("Hello"); 
    var tvps = new TokenValidationParameters 
    { 
     // The web app and the service are sharing the same clientId 
     ValidAudience = clientId, 
     ValidateIssuer = false, 
    }; 

    // NOTE: The usual WindowsAzureActiveDirectoryBearerAuthenticaitonMiddleware uses a 
    // metadata endpoint which is not supported by the v2.0 endpoint. Instead, this 
    // OpenIdConenctCachingSecurityTokenProvider can be used to fetch & use the OpenIdConnect 
    // metadata document. 

    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions 
    { 
     AccessTokenFormat = new JwtFormat(tvps, new OpenIdConnectCachingSecurityTokenProvider("https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration")), 
    }); 
} 

}關於通過Azure的AD V2.0端點保護網絡API

更多細節,您可以參閱以下文件:

Calling a web API from a .NET web app

+0

謝謝!與此同時,我採用了AD V1.0,並且工作得很好,因爲我可以指定一個資源。所以我現在已經開始玩了,但我也會在有空的時候測試一下你的解決方案。 – Hinrich