如何验证 Azure AD 安全令牌? [英] How to validate Azure AD security token?

查看:21
本文介绍了如何验证 Azure AD 安全令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The following code gives me Azure AD security token, I need to validate that token is valid or not. How to achieve this?

// 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?                

推荐答案

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

There are two steps to verify the token. First, verify the signature of the token to ensure the token was issued by Azure Active Directory. Second, verify the claims in the token based on the business logic.

例如,如果您正在开发单租户应用程序,我们需要验证 issaud 声明.并且您还需要验证 nbf 以确保令牌未过期.更多声明可以参考此处.

For example, we need to verify the iss and aud claim if you were developing a single tenant app. And you also need to verify the nbf to ensure the token is not expired. More claims you can refer here.

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

Below description is from here about the detail of signature verifying. (Note: The example below uses the Azure AD v2 endpoint. You should use the endpoint that corresponds to the endpoint the client app is using.)

来自 Azure AD 的访问令牌是一个 JSON Web 令牌 (JWT),由安全令牌服务以私钥签名.

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

JWT 包括 3 部分:头部、数据和签名.从技术上讲,我们可以使用公钥来验证访问令牌.

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 singing tokens (public key)

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

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

Then we can use the JwtSecurityTokenHandler to verify the token using the sample code below:

 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 tokendHandler = new JwtSecurityTokenHandler();

     SecurityToken jwt;

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

     return jwt as JwtSecurityToken;
 }

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

And if you were using the OWIN components in your project, it is more easy to verify the token. We can use the code below to verify the token:

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

然后我们可以使用下面的代码来验证令牌中的范围":

Then we can use the code below to verify the ‘scope’ in the 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 的代码示例:

And here is a code sample which protected the web API with Azure AD:

使用不记名令牌保护 Web API来自 Azure AD

这篇关于如何验证 Azure AD 安全令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆