【问题标题】:Azure Functions OAuth2 from email / password stored in database?来自存储在数据库中的电子邮件/密码的 Azure Functions OAuth2?
【发布时间】:2020-02-13 15:43:20
【问题描述】:

我有一个包含电子邮件和密码哈希的数据库。

我想保护来自 Azure Functions 的 http 触发器,以仅允许授权调用,这要归功于带有 BEARER 令牌的 Authorization 标头。

我想我会需要

  1. 一个 http 触发器,将从电子邮件/密码生成令牌
  2. 根据 Authorization 标头对用户进行授权和认证

有人可以帮助我了解如何创建自定义身份验证提供程序或使用现有的身份验证提供程序并配置 Azure Functions 以使用它吗?

【问题讨论】:

  • 是否需要 C# 代码示例进行身份验证?
  • 是 .NET Core C#

标签: c# azure authentication oauth-2.0 azure-functions


【解决方案1】:

Microsoft 身份平台支持OAuth 2.0 Resource Owner Password Credentials (ROPC) 授权,它允许应用程序通过直接处理用户的密码来登录用户。

从数据库中获取电子邮件(用户名)和密码,并发送以下请求以接收访问令牌。

POST {tenant}/oauth2/v2.0/token
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded

client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&scope=user.read%20openid%20profile%20offline_access
&username=MyUsername@myTenant.com
&password=SuperS3cret
&grant_type=password

【讨论】:

  • 您好,谢谢您,我认为所有用户都必须存在于 microsoft 平台上才能使其正常工作?
  • 是的,他们是 azure ad 中的用户,因此他们可以进行身份​​验证。
【解决方案2】:

你可以看看下面的代码 sn-p,我在 azure portal 上测试过,Azure Function V2:

#r "Newtonsoft.Json"
using Newtonsoft.Json;
using System.Net;
using System.Net.Http.Headers;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{


    try
    {
       //Parse query parameter

              log.LogInformation("C# HTTP trigger function processed a request.");

                //Read Request Body
                var content = await new StreamReader(req.Body).ReadToEndAsync();

                //Extract Request Body and Parse To Class
                UserAuthentication objUserInfo = JsonConvert.DeserializeObject<UserAuthentication>(content);

               //Message Container
                dynamic validationMessage;

              //Validate required param

            if (string.IsNullOrEmpty(objUserInfo.UserName.Trim()))
                {
                    validationMessage = new OkObjectResult("User name is required!");
                    return (IActionResult)validationMessage;

                }
            if (string.IsNullOrEmpty(objUserInfo.Password.Trim()))
                {
                    validationMessage = new OkObjectResult("Password is required!");
                    return (IActionResult)validationMessage;
                }



                // Authentication Token Request format
                string tokenUrl = $"https://login.microsoftonline.com/common/oauth2/token";
                var tokenRequest = new HttpRequestMessage(HttpMethod.Post, tokenUrl);

                tokenRequest.Content = new FormUrlEncodedContent(new Dictionary<string, string>
                {
                    ["grant_type"] = "password",
                    ["client_id"] = "YourApplicationId",
                    ["client_secret"] = "YourApplicationPassword",
                    ["resource"] = "https://graph.microsoft.com",
                    ["username"] = "" + objUserInfo.UserName + "",
                    ["password"] = "" + objUserInfo.Password + ""


                });

                // Request For Token Endpoint 

                using (var _client = new HttpClient())
                {
                    var tokenResponse = await _client.SendAsync(tokenRequest);
                    AccessTokenClass objAccessToken = JsonConvert.DeserializeObject<AccessTokenClass>(await tokenResponse.Content.ReadAsStringAsync());

                    // When Token Request Null
                    if (objAccessToken.access_token == null)
                    {
                        validationMessage = new OkObjectResult("Invalid Authentication! Please Check Your Credentials And Try Again!");
                        return (IActionResult)validationMessage;

                    }
                    else
                    {
                          return new OkObjectResult(objAccessToken.access_token);
                    }



                }



    }
    catch (Exception ex)
    {
            validationMessage = new OkObjectResult("Sorry something went wrong! Please check your given information and try again! {0}" + ex.Message);
            return (IActionResult)validationMessage;

    }
}

我用过的课程: UserAuthentication Class

public class UserAuthentication
    {

        public string UserName { get; set; }
        public string Password { get; set; }

    }
public class AzureFunctionCreateUserClass
    {

           public string access_token { get; set; }
           public string expires_in { get; set; }
           public string token_type { get; set; }
           public string resource { get; set; }

    }

注意:这是我在 azure function 上编写的 azure portal 示例。所以尝试在那里运行。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2011-12-15
    • 2021-10-07
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多