将 JSON Web 令牌 (JWT) 与 Azure Functions 结合使用(不使用 Active Directory) [英] Using JSON Web Tokens (JWT) with Azure Functions (WITHOUT using Active Directory)

查看:14
本文介绍了将 JSON Web 令牌 (JWT) 与 Azure Functions 结合使用(不使用 Active Directory)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确信已经有人这样做了,但是我还没有找到任何关于 Microsoft 实现 JWT 的文档.Microsoft 为其 JWT 库提供的官方文档基本上是一个空白页面,请参阅:

您可以创建一个具有匿名访问权限的 HttpTrigger 函数来进行用户日志记录,并在用户存在时返回 JWT 令牌.对于受保护的 REST API,您可以按照以下代码示例进行操作:

if(System.Security.Claims.ClaimsPrincipal.Current.Identity.IsAuthenticated){//TODO: 检索用户名声明return req.CreateResponse(HttpStatusCode.OK,(System.Security.Claims.ClaimsPrincipal.Current.Identity as ClaimsIdentity).Claims.Select(c => new { key = c.Type, value = c.Value }),"应用程序/json");}别的{return req.CreateResponse(HttpStatusCode.Unauthorized,"访问被拒绝!");}

要生成应用服务身份验证中使用的 JWT 令牌,您可以遵循 如何:为您的应用程序使用自定义身份验证和自定义 API 控制器下的代码 CustomAuthController来自阿德里安霍尔关于自定义身份验证的书中/a> 创建 JWT 令牌.

更新:

对于应用服务身份验证下的自定义身份验证方法,我只想让 op 利用 EasyAuth 提供的身份验证/授权.我对这种方法做了一些测试,发现它可以在我这边工作.Op 可以将用户名和密码发送到 HttpTrigger 进行身份验证,然后 HttpTrigger 后端需要验证用户信息,并使用 Microsoft.Azure.Mobile.Server.Login 包,用于向客户端发布应用服务身份验证令牌,然后客户端可以从 AuthenticationToken 财产.针对受保护 API 的后续请求可能如下所示:

https://<your-funapp-name>.azurewebsites.net/api/<httpTrigger-functionName>标头:x-zumo-auth:<AuthenticationToken>

注意:

对于这种方法,相关的 HttpTrigger 函数需要允许匿名访问,并且应用服务身份验证也需要选择允许匿名请求(无操作).否则,应用服务身份验证和功能级别身份验证都会验证请求.对于受保护的API,op需要手动添加System.Security.Claims.ClaimsPrincipal.Current.Identity.IsAuthenticated检查.

I am sure someone out there has already done this, but I have yet to find any documentation with regard to the Microsoft implementation of JWT. The official documentation from Microsoft for their JWT library is basically an empty page, see:

https://docs.microsoft.com/en-us/dotnet/framework/security/json-web-token-handler-api-reference

So, here is what I (and I am sure many others) would like to accomplish:

Definition: User ID = The username or email address used to log into a system.

AUTHENTICATION:

  1. A user logs in. The user fills in web form and the system sends (via HTTPS POST) the users ID and password (hashed) to the server in order to authenticate / validate the user.

  2. Server Authenticates user. The users ID and password are checked against the values saved in the database and if NOT valid, an invalid login response is returned to the caller.

  3. Create a JWT Token - ???? No documentation available!

  4. Return the JWT token to the caller - ???? - I assume in a header? via JSON, not sure -- again - no documentation.

Given the code below, can anyone provide a code example for steps 3 and 4?

  [FunctionName( "authenticate" )]
  public static async Task<HttpResponseMessage> Run( [HttpTrigger( AuthorizationLevel.Anonymous, "get", "post", Route = null )]HttpRequestMessage req, TraceWriter log )
  {

   // Step 1 - Get user ID and password from POST data

   /*
   * Step 2 - Verify user ID and password (compare against DB values)
   * If user ID or password is not valid, return Invalid User response
   */

   // Step 3 - Create JWT token - ????

   // Step 4 - Return JWT token - ????

  }

AUTHORIZATION:

Assuming the user was authenticated and now has a JWT token (I am assuming the JWT token is saved in the users session; if someone wants to provide more info, please do):

  1. A POST request is made to an Azure Function to do something (like get a users birth date). The JWT token obtained above is loaded (from the POST data or a header - does it matter?) along with any other data required by the function.

  2. The JWT token is validated - ???? No documentation available!

  3. If the JWT token is NOT valid, a BadRequest response is returned by the function.

  4. If the JWT token is valid, the function uses the data passed to it to process and issue a response.

Given the code below, can anyone provide a code example for steps 1 and 2?

  [FunctionName( "do_something" )]
  public static async Task<HttpResponseMessage> Run( [HttpTrigger( AuthorizationLevel.Anonymous, "get", "post", Route = null )]HttpRequestMessage req, TraceWriter log )
  {

   // Step 1 - Get JWT token (from POST data or headers?)

   // Step 2 - Validate the JWT token - ???

   // Step 3 - If JWT token is not valid, return BadRequest response

   // Step 4 - Process the request and return data as JSON

  }

Any and all information would really help those of us (me) understand how to use JWT with Azure (anonymous) functions in order to build a "secure" REST API.

Thanks in advance.

解决方案

Any and all information would really help those of us (me) understand how to use JWT with Azure (anonymous) functions in order to build a "secure" REST API.

Per my understanding, you could use the related library in your azure function code to generate / validate the JWT token. Here are some tutorials, you could refer to them:

Create and Consume JWT Tokens in C#.

Jwt.Net, a JWT (JSON Web Token) implementation for .NET

JWT Authentication for Asp.Net Web Api

Moreover, you could leverage App Service Authentication / Authorization to configure the function app level Authentication / Authorization. You could go to your Function App Settings, click "NETWORKING > Authentication / Authorization" under the Platform features tab. Enable App Service Authentication and choose Allow Anonymous requests (no action) as follows:

You could create a HttpTrigger function with anonymous accessing for user logging and return the JWT token if the user exists. For the protected REST APIs, you could follow the code sample below:

if(System.Security.Claims.ClaimsPrincipal.Current.Identity.IsAuthenticated)
{
   //TODO: retrieve the username claim
   return req.CreateResponse(HttpStatusCode.OK,(System.Security.Claims.ClaimsPrincipal.Current.Identity as ClaimsIdentity).Claims.Select(c => new { key = c.Type, value = c.Value }),"application/json");
}
else
{
    return req.CreateResponse(HttpStatusCode.Unauthorized,"Access Denied!"); 
}

For generating the JWT token used in App Service Authentication, you could follow How to: Use custom authentication for your application and the code under custom API controller CustomAuthController from adrian hall's book about Custom Authentication to create the JWT token.

UPDATE:

For the custom authentication approach under App Service Authentication, I just want op to leverage the authentication / Authorization provided by EasyAuth. I have did some test for this approach and found it could work on my side. Op could send the username and password to the HttpTrigger for authentication, then the HttpTrigger backend need to validate the user info, and use Microsoft.Azure.Mobile.Server.Login package for issuing App Service Authentication token to the client, then the client could retrieve the token from the AuthenticationToken property. The subsequent requests against the protected APIs could look like as follows:

https://<your-funapp-name>.azurewebsites.net/api/<httpTrigger-functionName>
Header: x-zumo-auth:<AuthenticationToken>

NOTE:

For this approach, the related HttpTrigger functions need to allow anonymous accessing and the App Service Authentication also needs to choose Allow Anonymous requests (no action). Otherwise, the App Service Authentication and function level authentication would both validate the request. For the protected APIs, op needs to manually add the System.Security.Claims.ClaimsPrincipal.Current.Identity.IsAuthenticated checking.

这篇关于将 JSON Web 令牌 (JWT) 与 Azure Functions 结合使用(不使用 Active Directory)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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