Azure Functions 的身份验证 [英] Authentication for Azure Functions

查看:40
本文介绍了Azure Functions 的身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在过去 24 小时内阅读了有关如何创建 Azure Functions 的所有内容,并已成功将 MVC WebApi 转换为具有多种功能的新函数应用程序.我的问题是我没有找到任何关于如何对它们进行最基本的身份验证的明确文档或教程.

我的场景非常简单.在我的 AAD 中配置用户,然后授予这些用户访问特定功能的权限.网站上的用户将单击 UI 元素,这些元素又会触发调用我的 Azure 函数的 Javascript.在函数中,我需要能够以某种方式验证它们的身份,因为我会将其传递给与 SQL 实例交互的其他函数.

有人可以给我指出文档、文章、示例或其他内容,以显示我如何实现这一目标吗?

作为记录,我在门户中找到了我的函数应用程序的身份验证"配置,并选择了 AAD 作为我的身份验证提供程序.我已将我的 Function App 添加到其中并配置了一些用户.然后我编写了以下测试函数:

[FunctionName("GetThings")]public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.User, "GET", Route = null)]HttpRequestMessage req, TraceWriter log){log.Info("获取所有信息");var identity = ClaimsPrincipal.Current.Identity;返回身份.IsAuthenticated ?req.CreateResponse(HttpStatusCode.Unauthorized, "未通过身份验证!") :req.CreateResponse(HttpStatusCode.OK, $"Hi {identity.Name}!");}

目前,当我尝试直接访问端点时,我被重定向到登录页面......所以我猜这部分正在工作.我如何生成/检索用户令牌,将它们发送到函数的请求中,或者在服务器上处理它们,但我不清楚.

帮助?

解决方案

一旦用户通过 Azure AD 进行身份验证,您将看到一个 AppServiceAuthSessoin cookie.这是一个不透明的 cookie,但您可以通过调用将其交换为可读的 id 令牌

https://yourFunctionApp.azurewebsites.net/.auth/me

并将不透明的 cookie 作为 Cookie 标头传入.此外,您返回的 id_token 可以用作 Bearer 令牌.

实际上它只是对我来说看起来很合适,我还没有真正测试过它作为承载者,所以在那里有点谨慎.

该机制称为Easy Auth,Google 更容易找到该名称.

这里有更多关于代币商店的信息 —
https://cgillum.tech/2016/03/07/app-service-token-store/

...这表示您可以通过读取来自用户浏览器的 HTTP 标头来获取声明:

<块引用>

访问令牌

<块引用>

在您的后端代码中,访问这些令牌就像读取 HTTP 请求标头一样简单.标头的名称类似于 X-MS-TOKEN-{provider}-{type}.下面列出了可能的令牌标头名称:

<块引用>

Azure Active Directory 令牌请求标头:

X-MS-TOKEN-AAD-ID-TOKENX-MS-TOKEN-AAD-ACCESS-TOKENX-MS-TOKEN-AAD-EXPIRES-ONX-MS-TOKEN-AAD-REFRESH-TOKEN

实际上我现在才发现,所以感谢您的提问!

更新:

我的预感是对的,id_token 也适合作为承载:

$ curl -isk https://{funcApp}.azurewebsites.net/api/{someFunc} -H 授权:持有人 eyJ0eXAiOi....oEU-Q"HTTP/1.1 200 正常缓存控制:无缓存服务器:Microsoft-IIS/8.0...

两种读取声明的方式(读取标题与使用用户的 Cookie 从后端调用 /.auth/me)之间的主要区别在于您获得的详细信息量.后者还有更多.

这是您从 Easy Auth 获得的一组 标头,用于 Twitter 身份验证用户:

{cookie":AppServiceAuthSession=Lx43...xHDTA==",...x-ms-client-principal-name":evilSnobu",x-ms-client-principal-id":35....",x-ms-client-principal-idp":推特",x-ms-token-twitter-access-token":35...Dj",x-ms-token-twitter-access-token-secret":OK3...Jx",}

以及您通过调用 /.auth/me 获得的声明:

{access_token":35...FDj",access_token_secret":OK3...sJx",provider_name":推特",用户声明":[{类型":http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier",val":352660979"},{典型":http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn",val":evilSnobu"},{典型":http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",val":Safarihat 黑客"},{典型":http://schemas.xmlsoap.org/ws/2005/05/identity/claims/webpage",val":……"},{typ":urn:twitter:description",瓦尔":天才".有大脑.会旅行."},{typ":urn:twitter:location",val":"},{类型":urn:twitter:time_zone",val":伦敦"},{typ":urn:twitter:lang",val":en"},{typ":urn:twitter:verified",val":假"},{类型":urn:twitter:profile_image_url_https",val":https://pbs.twimg.com/profile_images/867473646876545024/1elebfK1_normal.jpg";}],user_id":evilSnobu"}

I've spent the past 24 hours reading all about how to create Azure Functions and have successfully converted a MVC WebApi over to a new Function App with multiple functions. My problem is that I've not found any clear documentation or tutorials on how to do the most basic of authentication with them.

My scenario is pretty straight forward. Provision users in my AAD, then grant those users access to specific functions. Users on a website will click on UI elements that in turn trigger Javascript that calls my Azure Functions. In the function I need to be able to verify their identity somehow as I'll be passing that along to other functions that interact with a SQL instance.

Can someone please point me at docs, articles, an example, something, that shows how I can achieve this?

For the record I've found in the portal the "Authentication" config for my Function App and have chosen AAD as my Authentication Provider. I've added my Function App to it and have provisioned a few users. I've then wrote the following test function:

[FunctionName("GetThings")]
public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.User, "GET", Route = null)]HttpRequestMessage req, TraceWriter log)
{
    log.Info("Getting all the things");
    var identity = ClaimsPrincipal.Current.Identity;

    return identity.IsAuthenticated ?
        req.CreateResponse(HttpStatusCode.Unauthorized, "Not authenticated!") :
        req.CreateResponse(HttpStatusCode.OK, $"Hi {identity.Name}!");
}

Currently when trying to hit the endpoint directly I get redirected to a login page... so I guess that part is working. How I generate / retrieve user tokens, send them along on the request to the functions, or process them on the server isn't clear to me though.

Help?

解决方案

Once the user authenticates with Azure AD you'll be presented an AppServiceAuthSessoin cookie. It's an opaque cookie but you can exchange it for a readable id token by calling

https://yourFunctionApp.azurewebsites.net/.auth/me

and passing in the opaque cookie as Cookie header. Moreover, the id_token you get back is good for use as Bearer token.

Actually it just looks right to me, i haven't really tested it as a Bearer, so a little caution there.

The mechanism is called Easy Auth, it's easier to Google for that name.

More on the token store here —
https://cgillum.tech/2016/03/07/app-service-token-store/

...which says you can grab the claims just by reading the HTTP headers coming in from the user's browser:

Accessing the Tokens

From within your backend code, accessing these tokens is as easy as reading an HTTP request header. The headers are named like X-MS-TOKEN-{provider}-{type}. The possible token header names are listed below:

Azure Active Directory Token Request Headers:

X-MS-TOKEN-AAD-ID-TOKEN
X-MS-TOKEN-AAD-ACCESS-TOKEN
X-MS-TOKEN-AAD-EXPIRES-ON
X-MS-TOKEN-AAD-REFRESH-TOKEN

I actually just found that out right now, so thanks for the question!

UPDATE:

My hunch was correct, the id_token is also good as Bearer:

$ curl -isk https://{funcApp}.azurewebsites.net/api/{someFunc} 
       -H "Authorization: Bearer eyJ0eXAiOi....oEU-Q"

HTTP/1.1 200 OK
Cache-Control: no-cache
Server: Microsoft-IIS/8.0
...

The main difference between the two ways of reading claims (reading headers vs. calling /.auth/me from the backend with user's Cookie) is the amount of detail you get. There's way more in the latter.

Here's the set of headers you get from Easy Auth for a Twitter authenticated user:

{
   "cookie": "AppServiceAuthSession=Lx43...xHDTA==",
   ...
   "x-ms-client-principal-name": "evilSnobu",
   "x-ms-client-principal-id": "35....",
   "x-ms-client-principal-idp": "twitter",
   "x-ms-token-twitter-access-token": "35...Dj",
   "x-ms-token-twitter-access-token-secret": "OK3...Jx",
}

and the claims you get by calling /.auth/me:

{
   "access_token": "35...FDj",
   "access_token_secret": "OK3...sJx",
   "provider_name": "twitter",
   "user_claims": [
      {
         "typ": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier",
         "val": "352660979"
      },
      {
         "typ": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn",
         "val": "evilSnobu"
      },
      {
         "typ": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",
         "val": "Safarihat Hacker"
      },
      {
         "typ": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/webpage",
         "val": "..."
      },
      {
         "typ": "urn:twitter:description",
         "val": "GENIUS. HAVE BRAIN. WILL TRAVEL."
      },
      {
         "typ": "urn:twitter:location",
         "val": ""
      },
      {
         "typ": "urn:twitter:time_zone",
         "val": "London"
      },
      {
         "typ": "urn:twitter:lang",
         "val": "en"
      },
      {
         "typ": "urn:twitter:verified",
         "val": "False"
      },
      {
         "typ": "urn:twitter:profile_image_url_https",
         "val": "https://pbs.twimg.com/profile_images/867473646876545024/1elebfK1_normal.jpg"
      }
   ],
   "user_id": "evilSnobu"
}

这篇关于Azure Functions 的身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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