在C#REST服务中验证ADAL JWT令牌 [英] Validating ADAL JWT token in C# REST service

查看:165
本文介绍了在C#REST服务中验证ADAL JWT令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web应用程序,该应用程序使用ADAL库通过Azure Active Directory进行身份验证.

I have a web application which uses the ADAL library for authentication through Azure Active Directory.

此Web应用程序通过传递ADAL令牌字符串作为参数来调用C#REST服务.在我的REST服务中,我想验证此令牌.如果令牌仅有效,则服务将执行操作.

This web application makes a call to a C# REST service by passing the ADAL token string as a parameter. In my REST service, I want to validate this token. If the token is valid only then the service will perform the operation.

我进行了很多搜索,但是找不到在我的rest服务中验证JWT令牌的方法.你们能帮我吗?

I searched a lot but could not find a way to validate the JWT token in my rest service. Can you guys please help me on this?

推荐答案

您有两个选择:

1.使用OWIN中间件

使用将为您处理令牌验证的中间件.一个常见的情况是OWIN中间件,它可以为您解决所有难题.通常,这是最好的方法,因为它使您可以将代码重点放在API的业务逻辑上,而不是低级令牌验证上.对于使用OWIN的REST API示例,请查看以下两个示例:

Use middleware that will handle token validation for you. A common case will be the OWIN middleware, which does all the magic for you. Usually, this is the best approach, as it allows you to focus your code on the business logic for your API, not on low-level token validation. For a sample REST API that uses OWIN, check out these two samples:

  • https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect
  • https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect-aspnet5

2.手动JWT验证

您可以使用ASP.NET的JSON Web令牌处理程序来进行手动JWT令牌验证. (好吧,这不完全是手动的,而是手动调用的.)还有一个示例:

You can use the JSON Web Token Handler for ASP.NET to do manual JWT token validation. (Ok, so it's not entirely manual, but it is manually invoked.) There's also a sample for this:

  • https://github.com/Azure-Samples/active-directory-dotnet-webapi-manual-jwt-validation (the actual JWT validation happens in Global.asax.cs and looks something like this:

JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();

TokenValidationParameters validationParameters = new TokenValidationParameters
{
    ValidAudience = audience,
    ValidIssuer = issuer,
    IssuerSigningTokens = signingTokens,
    CertificateValidator = X509CertificateValidator.None
};

try
{
    // Validate token.
    SecurityToken validatedToken = new JwtSecurityToken();
    ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken(jwtToken, validationParameters, out validatedToken);

    // Do other validation things, like making claims available to controller...
}
catch (SecurityTokenValidationException)
{
    // Token validation failed
    HttpResponseMessage response = BuildResponseErrorMessage(HttpStatusCode.Unauthorized);
    return response;
}

这篇关于在C#REST服务中验证ADAL JWT令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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