locked
Authorize attribute in MVC and Web API RRS feed

  • Question

  • User52625461 posted

    Hello All,

    After logging into the mvc application using authorize attribute, I am trying to call web api method which also has the Authorize attribute.

    However, at this is point it is giving me unauthorized error. Why this is so ?

    It should not give me such error as I have already logged into the application.

    My mvc application and web api are in 2 different projects.

    Any help on this appreciated !

    MVC Login Controller

     [Authorize]
        public class AccountController : Controller
        {
    
     [HttpPost]
            [AllowAnonymous]
            [ValidateAntiForgeryToken]
            public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
            {
                if (!ModelState.IsValid)
                {
                    return View(model);
                }
    
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, change to shouldLockout: true
                var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
                switch (result)
                {
                    case SignInStatus.Success:
                        return RedirectToLocal(returnUrl);
                    case SignInStatus.LockedOut:
                        return View("Lockout");
                    case SignInStatus.RequiresVerification:
                        return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
                    case SignInStatus.Failure:
                    default:
                        ModelState.AddModelError("", "Invalid login attempt.");
                        return View(model);
                }
            }
    
    }

    Calling WebApi method from MVC controller

     public ActionResult CallWebAPI()
            {
                try
                {
    
                    HttpClient client = new HttpClient();
                    Uri baseAddress = new Uri("http://localhost/WebAPI/api/values");
                    client.BaseAddress = baseAddress;
                    client.DefaultRequestHeaders.Accept.Clear();
                    var response = client.GetAsync(baseAddress).Result;
    
                    if (response != null) 
                    {
                        String err = response.Content.ReadAsStringAsync().Result;
                        TempData["key"] = err;
                    }
    
                    return RedirectToAction("Index", "Home");
                }
                catch (Exception ex)
                {
    
                    throw ex;
                }
            }

    Web API controller

    [Authorize]
        public class ValuesController : ApiController
        {
            // GET api/values
            public IEnumerable<string> Get()
            {
                return new string[] { "value1", "value2" };
            }
    }

    Wednesday, December 16, 2015 12:03 PM

Answers

  • User-219423983 posted

    Hi rohitpundlik,

    I have made a test about based on your description above and change the ValuesController “Authorize” to “System.Web.Mvc.Authorize”, but I still get the “Authorization has been denied for this request.”.

    So, in your case above, you could try to close your browser and clean all the cookies and passwords of your browser.

    Then, input the “http://localhost/WebAPI/api/values” to see whether you could get the expected result. In my test, it shows “Authorization has been denied for this request”.

    After that, you could enter your MVC application with your account and then check if the “Account/CallWebAPI” could return the API values. In my test, it still could not.

    So, I think, you’d better have a try to use the above suggestion above to achieve your need.

    Best Regards,

    Weibo Zhang

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, January 8, 2016 7:11 AM

All replies

  • User-1618234021 posted

    My mvc application and web api are in 2 different projects.

    If that is the case, you need to enable CORS on your web api project. See the following:

    http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

    Wednesday, December 16, 2015 1:01 PM
  • User-782957977 posted

    Looks like your approach will work only if you add MVC and Web Api controllers in same project.

    If you want to host MVC and Web Api as 2 different application, then try like this

    1) When user login to MVC application, call Web Api token handler to get Web Api token

    2) Include Web Api token in each Web api request from MVC. Following link explain how to get Web Api token and call Web api with authorization token

    http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api

    Thursday, December 17, 2015 3:55 AM
  • User52625461 posted

    Looks like your approach will work only if you add MVC and Web Api controllers in same project.

    If you want to host MVC and Web Api as 2 different application, then try like this

    1) When user login to MVC application, call Web Api token handler to get Web Api token

    2) Include Web Api token in each Web api request from MVC. Following link explain how to get Web Api token and call Web api with authorization token

    http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api

    Thanks for the reply ! 

    However, I have done small change by referencing the Authorize attribute from Syste.Web.MVC dll in both projects and it starts working. Web api uses Authorize attribute from System.Web.Http.Filters.AuthorizationFilterAttribute

    Is this correct approach ?

    Thursday, December 17, 2015 4:12 AM
  • User-219423983 posted

    Hi rohitpundlik,

    I have made a test about based on your description above and change the ValuesController “Authorize” to “System.Web.Mvc.Authorize”, but I still get the “Authorization has been denied for this request.”.

    So, in your case above, you could try to close your browser and clean all the cookies and passwords of your browser.

    Then, input the “http://localhost/WebAPI/api/values” to see whether you could get the expected result. In my test, it shows “Authorization has been denied for this request”.

    After that, you could enter your MVC application with your account and then check if the “Account/CallWebAPI” could return the API values. In my test, it still could not.

    So, I think, you’d better have a try to use the above suggestion above to achieve your need.

    Best Regards,

    Weibo Zhang

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, January 8, 2016 7:11 AM