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

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

问题描述

以下代码给了我Azure AD security token,我需要验证令牌是否有效.如何实现呢?

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.

以下描述来自

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:

使用Bearer令牌保护Web API从Azure AD

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

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