简体   繁体   English

在C#REST服务中验证ADAL JWT令牌

[英]Validating ADAL JWT token in C# REST service

I have a web application which uses the ADAL library for authentication through Azure Active Directory. 我有一个Web应用程序,它使用ADAL库通过Azure Active Directory进行身份验证。

This web application makes a call to a C# REST service by passing the ADAL token string as a parameter. 此Web应用程序通过将ADAL标记字符串作为参数传递来调用C#REST服务。 In my REST service, I want to validate this token. 在我的REST服务中,我想验证此令牌。 If the token is valid only then the service will perform the operation. 如果令牌有效,则服务将执行该操作。

I searched a lot but could not find a way to validate the JWT token in my rest service. 我搜索了很多,但找不到在我的休息服务中验证JWT令牌的方法。 Can you guys please help me on this? 你能帮帮我吗?

You have two options: 您有两种选择:

1. Use OWIN middleware 1.使用OWIN中间件

Use middleware that will handle token validation for you. 使用将为您处理令牌验证的中间件。 A common case will be the OWIN middleware, which does all the magic for you. 一个常见的案例是OWIN中间件,它为您提供了所有的魔力。 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. 通常,这是最好的方法,因为它允许您将代码集中在API的业务逻辑上,而不是低级别的令牌验证。 For a sample REST API that uses OWIN, check out these two samples: 有关使用OWIN的示例REST API,请查看以下两个示例:

2. Manual JWT validation 2.手动JWT验证

You can use the JSON Web Token Handler for ASP.NET to do manual JWT token validation. 您可以使用JSON Web Token Handler for ASP.NET进行手动JWT令牌验证。 (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: https://github.com/Azure-Samples/active-directory-dotnet-webapi-manual-jwt-validation (实际的JWT验证发生在Global.asax.cs中 ,看起来像这样:

     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; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM