0

I have a database that contains emails and password hashes.

I would like to secure http trigger's from Azure Functions to allow only authorized call thanks to the Authorization header with a BEARER token.

I think I will need

  1. an http trigger that will generate the token from email/password
  2. Authorize and authenticate the user based on the Authorization header

Can someone get me started on how to create a custom authentication provider or use an existing one and configure Azure Functions to work with it?

Md Farid Uddin Kiron
  • 16,817
  • 3
  • 17
  • 43
fred_
  • 1,486
  • 1
  • 19
  • 31

2 Answers2

0

Microsoft identity platform supports the OAuth 2.0 Resource Owner Password Credentials (ROPC) grant, which allows an application to sign in the user by directly handling their password.

Get the email(username) and password from database, and send the following request to receive the access token.

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
Joey Cai
  • 18,968
  • 1
  • 20
  • 30
0

You could have look following code snippet, I have tested on 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;

    }
}

Class I have Used: 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; }

    }

Note: This an sample for azure portal which I have written on azure function . So try to run on there.

Hope this would help.

Md Farid Uddin Kiron
  • 16,817
  • 3
  • 17
  • 43