2

I am new to Azure, C# and Web API so first of all i'd like to apologize in advance cause this may sound like a stupid question.

I just want to know if it is possible that while I'm developing my C# Web API and my frontend web app locally is I am already using Azure's authentication? Like authenticate by using someone's Microsoft account?

Thanks!

EDIT

So i've already set up the app based on this link: https://learn.microsoft.com/en-us/azure/app-service-mobile/app-service-mobile-how-to-configure-microsoft-authentication

On my frontend web app when the user is not authenticated it gets redirected to Microsoft's login page, when I tried to login I get the error below:

enter image description here

Also please note I haven't deployed anything to Azure yet, my codes are still local I just need the authentication for now.

Hope someone can help me again.

Thanks

UPDATE

So I was able to implement MSAL by using the msalx library created by someone which made it possible to integrate msal in Angular. I already can get the access token after logging in using my personal Microsoft account, but the problem is when I access my Web API it always says 401 Unauthorized.

Thanks in advance!

enter image description here

Jed
  • 1,054
  • 1
  • 15
  • 34

2 Answers2

2

Based on my understanding, you are trying to authenticate users with their Microsoft Account.

Here's a useful guide on how to setup and enable your web app to use authentication based on Microsoft's account.

https://learn.microsoft.com/en-us/azure/app-service-mobile/app-service-mobile-how-to-configure-microsoft-authentication

Besides, it's a Yes that you can test it locally after setting up and configuring your local app.

Here's a GitHub repo sample web app which use Microsoft Account authentication.

https://github.com/lexdevel/MicrosoftAccountAuthentication

juvchan
  • 6,113
  • 2
  • 22
  • 35
1

AFAIK, for using App Service Authentication / Authorization, your C# Web API need to be deployed to azure. App Service Authentication / Authorization (Easy Auth) is a feature of Azure App Service and is implemented as a native IIS module that runs in the same sandbox as your azure application. For more details, you could refer to Architecture of Azure App Service Authentication / Authorization.

Based on your scenario, you could refer to the following approaches:

Use App Service Authentication / Authorization (Easy Auth)

  • configure your App Service application to use Microsoft Account login

  • Access https://{your-appname}.azurewebsites.net/.auth/login/microsoftaccount via the browser to ensure that your have successfully set up your Web API and only the users authenticated by Microsoft account could access your Web API

  • For your front-end web app, you could leverage the JavaScript client library for Azure Mobile Apps for logging and retrieve the authenticationToken and userId, then you could set the x-zumo-auth request header with the value authenticationToken as the token for accessing your Web API as follows:

    enter image description here

    For more details about how to authenticate the user, you could refer to How to: Authenticate users.

    Note: For your local SPA, you need to configure the CORS setting and add ALLOWED EXTERNAL REDIRECT URLS under "SETTINGS > Authentication / Authorization" of your azure web app. For more details, you could refer to this issue.

Set up the authentication in your Web API

  • You could set up your OAuth 2.0 Bearer authentication, with AD v2.0 endpoint you could protect your Web API with both person MSA and work or school accounts. For how to build your Web API, you could refer to Secure an MVC web API.

  • For your front-end web app, you could leverage MSAL.js library for logging and retrieve the access_token, and use the token for calling your Web API HTTP bearer request.

UPDATE:

I used the TodoListService project from AppModelv2-WebAPI-DotNet, then use the following html for my client as follows:

<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
    <meta charset="utf-8" />

    <!-- IE support: add promises polyfill before msal.js  -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js" class="pre"></script>
    <script src="https://secure.aadcdn.microsoftonline-p.com/lib/0.1.1/js/msal.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
    <script class="pre">
    var userAgentApplication = new Msal.UserAgentApplication("b3dd78af-d9da-459d-bf01-f87104d87450", null, function (errorDes, token, error, tokenType) {
        // this callback is called after loginRedirect OR acquireTokenRedirect (not used for loginPopup/aquireTokenPopup)
    });

    userAgentApplication.loginPopup(["user.read"]).then(function (token) {
        var user = userAgentApplication.getUser();
        console.log(user);
        console.log('access token:' + token);

        InvokeApi(token);

    }, function (error) {
        alert('login error:' + error);
    });

    function InvokeApi(token) {
        $.ajax({
            type: "GET",
            url: "http://localhost:9184/api/values",
            headers: {
                'Authorization': 'Bearer ' + token,
            },
        }).done(function (data) {
            console.log('invoked Web API \'http://localhost:9184/api/values\' with result: ' + data);
            alert(data);
        }).fail(function (jqXHR, textStatus) {
            alert('Error getting data');
        });
    }
    </script>
</body>
</html>

Result:

enter image description here

Additionally, you could refer to this git sample JavaScript Single Page Application with an ASP.NET backend, using msal.js.

Bruce Chen
  • 18,207
  • 2
  • 21
  • 35
  • So in essence I can only use Azure's authentication if my API or app is already deployed there? Is there a way where I can authenticate users using their Microsoft account without deploying to Azure? – Jed Aug 29 '17 at 04:30
  • 1
    For the build-in Easy Auth feature, you could only use it on Azure for now. Based on your requirement, you could leverage the option 2, then your web api could run without deploying to Azure. You could follow the above tutorials for building your web api and use MSAL.js for authentication with MSA, then use the token for accessing your web api. – Bruce Chen Aug 29 '17 at 05:56
  • Okay which means also that I don't need to have a subscription in Azure when developing web apps that will later be deployed there? Btw, thank you for your answer it clarified my requirements. I'll be going with the second option. – Jed Aug 29 '17 at 07:07
  • Yes, you could develop it locally, then deploy it to azure later. Any concerns when implementing your application, feel free to let us know. – Bruce Chen Aug 29 '17 at 07:16
  • Yeah so i've followed option no. 2 and was able to implement but i'm getting the error: `Msal.UserAgentApplication is not a constructor`, any idea? – Jed Aug 29 '17 at 22:01
  • 1
    I updated my answer with some test and tutorial, you could refer to them. – Bruce Chen Aug 30 '17 at 01:26
  • Yes I also based it there, I guess the difference is i'm using Angular and Typescript which is why i'm using the msal.d.ts file – Jed Aug 30 '17 at 02:14
  • I also tried just running your code above i'm getting the following error: `the provided value for input parameter 'redirect_uri' is not valid`, this is after logging in on the popup login window. my redirect url on my application in apps.dev.microsoft.com is the localhost:port as instructed on the tutorial. – Jed Aug 30 '17 at 07:19
  • The login window is opened from `http://localhost:9184/login.html`, you need to add it to the Redirect URLs of your web platform under your app. Also, you need to check the "Implicit Flow" checkbox. – Bruce Chen Aug 30 '17 at 07:27
  • Hi, I was able to make the frontend work. I updated my question again. Please see. Thanks – Jed Aug 31 '17 at 06:26
  • Just leverage postman or fiddler to simulate the request against your WebApi with the retrieved access_token as the bearer token to narrow this issue, could you see any detailed response (body or headers)? – Bruce Chen Aug 31 '17 at 06:34
  • For your webapi, just check [Configure OAuth authentication](https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-devquickstarts-dotnet-api#configure-oauth-authentication). Per my understanding, the middleware would check the `ValidAudience` (Application Id of your app), you could leverage [jwt.io](https://jwt.io/) to decode your access token and check the `aud` property. – Bruce Chen Aug 31 '17 at 06:52
  • I think that documentation of Configure OAuth authentication is outdated cause on the code that I am working there's no constructor for JwtFormat that accepts the params TokenValidationParameters and OpenIdConnectCachingSecurityTokenProvider. – Jed Aug 31 '17 at 07:44
  • The backend is still the problem here. It doesn't accept the token generated using msal.js. – Jed Sep 02 '17 at 00:03
  • I think I was asking the wrong questions, your answer here: https://stackoverflow.com/questions/44413587/use-msal-auth-token-to-consume-web-api-2 is more clear and my apps are working now, thanks a lot! – Jed Sep 02 '17 at 01:10