gpt4 book ai didi

c# - 如何验证 Azure AD 安全 token ?

转载 作者:IT王子 更新时间:2023-10-29 04:48:23 24 4
gpt4 key购买 nike

以下代码为我提供了Azure AD 安全 token ,我需要验证该 token 是否有效。如何实现这一目标?

// Get OAuth token using client credentials 
string tenantName = "mytest.onmicrosoft.com";
string authString = "https://login.microsoftonline.com/" + tenantName;

AuthenticationContext authenticationContext = new AuthenticationContext(authString, false);

// Config for OAuth client credentials
string clientId = "fffff33-6666-4888-a4tt-fbttt44444";
string key = "123v47o=";
ClientCredential clientCred = new ClientCredential(clientId, key);
string resource = "http://mytest.westus.cloudapp.azure.com";
string token;

Task<AuthenticationResult> authenticationResult = authenticationContext.AcquireTokenAsync(resource, clientCred);
token = authenticationResult.Result.AccessToken;
Console.WriteLine(token);
// How can I validate this token inside my service?

最佳答案

验证 token 有两个步骤。首先,验证 token 的签名以确保 token 是由 Azure Active Directory 颁发的。其次,根据业务逻辑验证 token 中的声明。

例如,如果您正在开发单租户应用,我们需要验证 issaud 声明。并且您还需要验证nbf以确保 token 没有过期。更多理赔可以引用here .

以下描述来自here关于签名验证的细节。 (注意:下面的示例使用 Azure AD v2 端点。您应该使用与客户端应用程序正在使用的端点相对应的端点。)

The access token from the Azure AD is a JSON Web Token(JWT) which is signed by Security Token Service in private key.

The JWT includes 3 parts: header, data, and signature. Technically, we can use the public key to validate the access token.

First step – retrieve and cache the signing tokens (public key)

Endpoint: https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration

然后我们可以使用 JwtSecurityTokenHandler 使用下面的示例代码来验证 token :

 public JwtSecurityToken Validate(string token)
{
string stsDiscoveryEndpoint = "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration";

ConfigurationManager<OpenIdConnectConfiguration> configManager = new ConfigurationManager<OpenIdConnectConfiguration>(stsDiscoveryEndpoint);

OpenIdConnectConfiguration config = configManager.GetConfigurationAsync().Result;

TokenValidationParameters validationParameters = new TokenValidationParameters
{
ValidateAudience = false,
ValidateIssuer = false,
IssuerSigningTokens = config.SigningTokens,
ValidateLifetime = false
};

JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();

SecurityToken jwt;

var result = tokenHandler.ValidateToken(token, validationParameters, out jwt);

return jwt as JwtSecurityToken;
}

如果您在项目中使用 OWIN 组件,则验证 token 会更容易。我们可以使用下面的代码来验证 token :

app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Audience = ConfigurationManager.AppSettings["ida:Audience"],
Tenant = ConfigurationManager.AppSettings["ida:Tenant"]
});

然后我们可以使用下面的代码来验证 token 中的“范围”:

public IEnumerable<TodoItem> Get()
{
// user_impersonation is the default permission exposed by applications in AAD
if (ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope").Value != "user_impersonation")
{
throw new HttpResponseException(new HttpResponseMessage {
StatusCode = HttpStatusCode.Unauthorized,
ReasonPhrase = "The Scope claim does not contain 'user_impersonation' or scope claim not found"
});
}
...
}

下面是使用 Azure AD 保护 Web API 的代码示例:

Protect a Web API using Bearer tokens from Azure AD

关于c# - 如何验证 Azure AD 安全 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39866513/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com