0

I currently have an issue with one of my apps.

The issue is that a user can keep the page open for a prolonged period of time before entering any data, so occasionally, when they enter data and hit the submit button, they are redirected to o365 for authentication and therefore lose the entered data.

I have all the standard authentication working for the app. However, i believe in order to do this, i would need to get a refreshed token in javascript when the submit button is clicked, and send this token to an api method in order to give access.

Is this possible and does anybody know how to go about it?

It is an MVC ASP.NET application using Owin O365 security with Microsoft Azure AD.

I am not sure what information or code snippets would be relevant here so if there is anything i can provide, please ask.

I have found multiple examples of getting tokens etc with angular, however, this is not an SPA and does not use angular.

Many Thanks in advance.

UPDATE

I have attempted to retrieve a token using ADAL JS using the following code but it doesnt seem to recognise the AuthorizationContext(config) call:

    <script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.0/js/adal.min.js"></script>

    $('#btnSubmit').on('click', function (e) {
        e.preventDefault();
        CheckUserAuthorised();
    });

    function CheckUserAuthorised() {
        window.config = {
            instance: 'https://login.microsoftonline.com/',
            tenant: '##################',
            clientId: '###################',
            postLogoutRedirectUri: window.location.origin,
            cacheLocation: 'localStorage'
        };
        var authContext = new AuthorizationContext(config); //THIS LINE FAILS
        var user = authContext.getCachedUser();
        if (!user) {
            alert("User Not Authorised");
            authContext.login();
        }
        else {
            alert('User Authorized');
        }
    }

This gives the following error in console:

'AuthorizationContext' is undefined

UPDATE

I have no got passed the undefined error. This was because i was calling AuthorizationContext rather than AuthenticationContext. Schoolboy error. However now, whenever i check the user property of the context, it is always null. And i do not know a way around this as the context is initialised on page load.

DaRoGa
  • 2,196
  • 8
  • 34
  • 62
  • There's a typo in your code. Try changing AuthorisationContext to AuthorizationContext. – n0m4d Jul 26 '16 at 13:21
  • good spot and thank you for that but i still get the error: `AuthorizationContext is undefined` – DaRoGa Jul 26 '16 at 13:39
  • Where did you get this code sample? Another thing: Instead of passing to the AuthorizationContext the config, pass that as window.config because config was defined in the window object. – n0m4d Jul 26 '16 at 13:53
  • https://github.com/Azure-Samples/active-directory-javascript-singlepageapp-dotnet-webapi/blob/master/TodoSPA/App/Scripts/app.js and http://nickvandenheuvel.eu/2016/01/06/authenticate-an-office-365-user-with-adal-js/ is what ive been using to generate my code – DaRoGa Jul 26 '16 at 14:50

2 Answers2

0

I found a similar example on the web and your problem seems to be related to the object you are instantiating.

Instead of

new AuthorizationContext(window.config);

try

new AuthenticationContext(window.config);

The code ran just fine showing that the user was not authenticated.

n0m4d
  • 832
  • 6
  • 12
  • hi yes i spotted this too, i am no longer receiving the undefined error, however, now user is always null, i pass in the parameters and do if(!user){authContext.login()} etc but because the instantiation is always done on page load, user is always null. how can i get around this? – DaRoGa Jul 26 '16 at 14:49
  • When you pass in the parameters to the url and try running that on the browser, do you get any response? – n0m4d Jul 26 '16 at 14:52
  • When i call .login(), the browser redirects and returns an id_token in the url in the format `https://localhost:44300/Communication/Add#id_token=ey.............&session_state=.....` – DaRoGa Jul 26 '16 at 14:53
0

There is a lack of a step in your code, here is a simple code sample, hope it will help you:

<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.10/js/adal.min.js"></script>

<body>
<a href="#" onclick="login();">login</a>
<a href="#" onclick="getToken()">access token</a>
<a href="#" onclick="getUser()">get user</a>
</body>
<script type="text/javascript">
    var configOptions = {
        tenant: "<tenant_id>", // Optional by default, it sends common
        clientId: "<client_id>",
        postLogoutRedirectUri: window.location.origin,
    }
    window.authContext = new AuthenticationContext(configOptions);

    var isCallback = authContext.isCallback(window.location.hash);
    authContext.handleWindowCallback();

    function getToken(){
        authContext.acquireToken("https://graph.microsoft.com",function(error, token){
            console.log(error);
            console.log(token);
        })
    }
    function login(){
        authContext.login();
    }
    function getUser(){
        var user = authContext.getCachedUser();
        console.log(user);
    }
</script>

The code sample is from the answer of No 'Access-Control-Allow-Origin' header with Microsoft Online Auth. The issues are different but they are in the same scenario.

any further concern, please feel free to let me know.

Community
  • 1
  • 1
Gary Liu
  • 13,758
  • 1
  • 17
  • 32
  • Thats great thanks i will try that now. In regards to the issues with IE, is that for Edge as well and is it only limited to localhost, so when deployed it wont matter which browser? As most of my users, use IE or Edge? Thanks again – DaRoGa Jul 27 '16 at 07:53
  • also, is there a way to acquire the token / login without redirecting the browser to microsoft? Essentially i am trying to do it so that i dont lose data entered onto the page and i can get a token, and pass it through to the API method as a parameter. Thanks, – DaRoGa Jul 27 '16 at 08:06
  • Im sorry if im being naive here, but i do not see how it works, when you first load the page, the authContext is initialised, at which point user will be null so login is needed before a token can be acquired. to login it redirects to microsoftonline to login and redirects back to original page at which point authContext is reinitialised and user will once again be null? or am i missing something? – DaRoGa Jul 27 '16 at 08:21
  • first initialize the `authContext`, and then `authContext.login();`, you can call either `authContext.getCachedUser()` or `authContext.acquireToken()` – Gary Liu Jul 27 '16 at 09:17
  • As the answer of http://stackoverflow.com/questions/38317973/no-access-control-allow-origin-header-with-microsoft-online-auth/38319300#38319300, ADAL for js does not support IE now. If you require IE, you can use https://github.com/AzureAD/azure-activedirectory-library-for-dotnet to implement the auth flow on your server side. – Gary Liu Jul 27 '16 at 09:19