简体   繁体   中英

WebAPI [Authorize] attribute. What is happening here?

I'm working on building a WebAPI AccountController with basic account functionality like LogIn, LogOut, Register, etc.

The top of my controller is decorated with the [System.Web.Http.Authorize] attribute.

In the following method, the user that is authenticated is my local system user unless I decorate the method with "AllowAnonymous":

    // GET/api/isAuthenticated
    // [System.Web.Http.AllowAnonymous]
    [System.Web.Http.HttpGet]
    public HttpResponseMessage IsAuthenticated()
    {
        if (User.Identity.IsAuthenticated)
        {
            var userProfile = _service.GetUserProfile(WebSecurity.CurrentUserId);
            return Request.CreateResponse(HttpStatusCode.OK, userProfile);
        }
        else
        {
            return Request.CreateResponse(HttpStatusCode.OK, false);
        }
    }

From what I understand, AllowAnonymous tells the controller to not apply the Authorize attribute to the given method. Since I'm building a web application, I never want to authorize against local credentials.

I pulled this code from the MVC SPA template so I'm wondering - how can this be changed to Authorize against the locally stored user credentials, instead of the system user, when [AllowAnonymous] isn't used?

When using WebAPI you should authenticate your users via HTTP Basic Authorization, its an HTTP standard for authorization. If you are logging via aspx page you should set your authorization in config section to forms authentication and if not, then you should add http authorization headers in your webapi calls.

WebAPI controller is different then normal controller and so are its authentication mechanisms.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM