2
votes

my project is composed from a webapi and a SPA application.

I try to implement authentication using Adal.js. this is my javascript code:

$(function () {
    var endpoints = {
        "https://demowebapi2017.azurewebsites.net/api/values/7": "WEB API ID"
    };
    window.config = {
        tenant: '7dda5c2-2fb6-4f82-...',
        clientId: 'CLIENT ID',
        endpoints: endpoints
    };
    window.authContext = new AuthenticationContext(config);


    $("#login").click(function () {
        window.authContext.login();
    });

    $("#logout").click(function () {
        window.authContext.logOut();
    });

    $("#clickMe").click(function () {
        var user = window.authContext.getCachedUser();
        console.log(user);

        window.authContext.acquireToken('https://demowebapi2017.azurewebsites.net', function (error, token) {
            console.log(error);
            console.log(token);
        }
            );
    });
});

Login works fine, I can see the login IFRAME for entering my credentials. When I click 'clickMe' I get the error message: 'User login is required' and user is null.

Everything works fine using Angular and Adal-angular.js, so I thing all Azure configuration is fine.

Has anybody have an idea about what happen?

1

1 Answers

1
votes

After you login, the app need to init the user from parsing the id_token from the hash. Here is the demo code for your reference:

$(function () {
    var endpoints = {
        "https://graph.windows.net": "https://graph.windows.net"
};
window.config = {
    tenant: 'xxxx.onmicrosoft.com',
    clientId: 'aac92cf9-32ab-4004-aeab-1046389dff79',
    endpoints: endpoints
};
window.authContext = new AuthenticationContext(config);


$("#login").click(function () {
    window.authContext.login();
});

$("#logout").click(function () {
    window.authContext.logOut();
});

$("#clickMe").click(function () {
    var user = window.authContext.getCachedUser();
    console.log(user);

    window.authContext.acquireToken('https://graph.windows.net', function (error, token) {
        console.log(error);
        console.log(token);
    }
        );
});

function init(){
    if(window.location.hash!="")
        window.authContext.handleWindowCallback(window.location.hash);
}

init();
});