Search code examples
c#asp.netrestasp.net-web-apistateless

Web Api 2 Stateless with Users


I believe I understand the basics of sessionless/stateless REST but I am having problems with implementation in Asp.Net Web Api 2 because I haven't used it before. I have set up ApiControllers that use a custom System.Web.Http.AuthorizeAttribute like this.

public class ApiAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
            if (actionContext.Request.Headers.Authorization != null)
            {
                //Set identity??
                return;
            }
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
    }
}

I have a database that contains users and I need to use them for getting privileges to get/post/put/delete things but dont want to use a session. I have never worked with the asp.net Identity so I am not familiar with its features and capabilities.

My idea for implementation is to use user credentials or api secret signing to authenticate and get privileges for a user for every request. The question is, by using a AuthorizeAttribute or something similar, how do i give the controller(s) during that one request the user information if their credentials were correct?

UPDATE: Is using this.User (ApiController.User) session based or can it be used for that single request. If so, how does one set it


Solution

  • It looks like that using IPrincipal and setting HttpContext.Current.User will allow the ApiControllers to access that user through using

    this.User
    

    with web api not having access to the session

    public override void OnAuthorization(HttpActionContext actionContext)
    {
            if (actionContext.Request.Headers.Authorization != null)
            {
                //Check user credentials/token here
                //Get internal user
    
                IPrincipal principal = new MyOwnCustomPrincipal(internalUser);
                HttpContext.Current.User = principal;
                return;
            }
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
    }