AngularJS reading parameters from url with hash

352 Views Asked by At

I am using ASP.NET SPA template, but remaking it to work with AngularJS instead of KnockoutJS. The thing, I have trouble with, is with authorization access token. By default in this template, authorization access token is retrieved, by redirecting user to /Account/Authorize?client_id=web&response_type=token, after that, user is redirected to home with /#access_token=TOKEN_HERE&token_type=bearer&expires_in=1209600 as an arguments. In KO template, there is this common object with function getFragment which reads this url argument, and returns this access token. In template, there is this code, which executes every time page is reloaded

        if (!dataModel.getAccessToken()) {
            // The following code looks for a fragment in the URL to get the access token which will be
            // used to call the protected Web API resource
            var fragment = common.getFragment();

            if (fragment.access_token) {
                // returning with access token, restore old hash, or at least hide token
                window.location.hash = fragment.state || '';
                dataModel.setAccessToken(fragment.access_token);
            } else {
                // no token - so bounce to Authorize endpoint in AccountController to sign in or register
                window.location = "/Account/Authorize?client_id=web&response_type=token&state=" + encodeURIComponent(window.location.hash);
            }
        }

dataModel.get/setAccessToken stores token as a variable in LocalStorage. I was trying to plug this piece of code into AngularJS controller, redirect user, if there is no access token in localstorage. But if I use ngRoute, it messes with response. It changes URL to default route, set in app.Config, and it clears returned token from URL before I can read it.

Can you help me figure out, how and where should I really use this?

1

There are 1 best solutions below

0
On

This is kind of a generic solution, I'd rip out the ASP.NET SPA stuff. Maybe with Knockout the ASP.NET SPA template provided some value but Angular can do all of what you're trying to do without having to fight your server side template.

Ideally your Angular application is treated like any other client (Android or iOS) to your backend services. Your backend API can expose all the functionality you need, including authentication - there's no reason to pull your user out of your Angular application just to authenticate.

If you would like to bootstrap your application an alternative to ASP.NET SPA would be to use a Yeoman generator. Try out the Angular Fullstack generator, it does a pretty good job of demonstrating how you can authenticate a user within your Angular application.