1

Summary:

Suppose I have a ASP.NET WebAPI2 Application as my back-end and for security it uses oAuth (bearer access tokens). Now i want to consume this Web API in my Ionic Application ( which uses AngularJS). What are the best practices to deal with the authorization and retrieval and refreshing access tokens in Ionic Framework?

More info:

Let's suppose i have +100 different AJAX calls to my web api. I want the functionality that if the server challenged an authentication (i.e no access token or it is expired), then i show the login form and eventually get the access token and save it for subsequent calls. And also somehow i should send the access token along with every other request. Obviously i can't write some code and duplicate it for each and every request that need authorization. So i'm looking for the best practices/implementations to handle authentication situations like this in Ionic Framework (AngularJS). Thanks in advance for any help.

1 Answer 1

1

You can use AngularJS interceptor for this task, it will be vary similar to the code below:

app.factory('authInterceptorService', ['$q', '$location', 'localStorageService', function ($q, $location, localStorageService) {

var authInterceptorServiceFactory = {};

var _request = function (config) {

    config.headers = config.headers || {};

    var authData = localStorageService.get('authorizationData');
    if (authData) {
        config.headers.Authorization = 'Bearer ' + authData.token;
    }

    return config;
}

var _responseError = function (rejection) {
    if (rejection.status === 401) {
        $location.path('/login');
    }
    return $q.reject(rejection);
}

authInterceptorServiceFactory.request = _request;
authInterceptorServiceFactory.responseError = _responseError;

return authInterceptorServiceFactory;

}]);

I have written detailed blog post on how to send access token from AngularJS app to Web Api back-end in a centralized place that you do not need to duplicate any code. You can check the post title "AngularJS Token Authentication using ASP.NET Web API 2, Owin, and Identity"

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.