Posting data from AngularJS to [Authorize] Action returns Login page HTML instead of Login page

705 Views Asked by At

I have created an ASP.Net MVC 4 project with AngularJS and there is a separate WebAPI layer. I am hitting to WebAPI method like this : AngularJS Post -> ASP.Net MVC Controller -> WebAPI method. I am doing this so as to allow only authorized [Authorize] users to access the ASP.Net MVC Controller method.

The issue I am facing is : When I put [Authorize] attribute on HomeController - the whole page is not accessible and what I see is the Login page. But when I put [Authorize] on Save action method - I get the HTML of Login page in AngularJS Post return instead of the Login page itself.

Please suggest what is it I am not doing correctly.

Below is my code -

ASP.Net MVC Controller :

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    [Authorize]
    public ActionResult Save()
    {
        // This will hit the WebApi to fetch data

        return View();
    }
}

AngularJS :

angular.module('TestApp', [])
.service('postDataSelfService', function ($http) {
    this.postDataSelf = function (controllerParam, actionParam) {
        debugger;
        var request = $http({
            method: 'POST',
            dataType: 'json',
            url: '/' + controllerParam + '/' + actionParam
        });

        return request;

    }
})
.controller('TestController', function ($scope, $http, postDataSelfService) {

    $scope.sendData = function (option) {

        var postData = postDataSelfService.postDataSelf('home', 'Save');
        postData.then(function (response) {
            if (response.data.length != 0) {
                debugger;
            }
            else {
                debugger;
            }
        },
         function (err) {
             debugger;
         });

    };
});
1

There are 1 best solutions below

0
On

As I did not get response on this, I am posting what I did.

Instead of checking for Authorized user in the Action method Save, I created another Action method just to check the User Status. I hit it from AngularJs just before calling Save, and send the User to login page from Angular if it is not logged in.