2

I am not sure if I am on the right track here, so I hoping someone can point me in the correct direction. I am writing a WEB API in C#, that I want different clients to be able to consume. The first one is an AngularJS client.

I am trying to create a log in portion. From my understanding, the way it is supposed to work is the client calls a login function with a username and password. Then upon successful authentication, the WEB API is supposed to pass back a token. This token is then passed back to the client every time a request is made.

I have the following login method on my controller:

public HttpResponseMessage Login([FromBody]CredentialContainer credentials)
{
    var response = new HttpResponseMessage();
    if (Authenticate(credentials.UserName, credentials.password)) 
    { 
       //Generate the token and set it on the response (but how?)
       response.StatusCode = HttpStatusCode.OK;
    }
    else 
    {
       response.StatusCode = HttpStatusCode.Unauthorized;
    }

    return response; 
}

How do I generate the token and then set it on the response, so it can be delivered back to the client? I have seen some examples using OAuth, but I don't want to use this, because it looks like you need to store the credentials in some OAuth DB. I want to store the credentials in the application's database though.

I also made the following attribute for if I do eventually understand how to set the token.

class MesssageAuthorizationAttribute : AuthorizeAttribute
{
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        //Validate Token here if I can get it from the actionContext?  
    }

    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
    {
       //not sure what to do here. Would not like the user to get a IIS credentials prompt.
    }
}

Do I have the correct approach here, or am I going about this all wrong?

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
Dave
  • 2,473
  • 2
  • 30
  • 55
  • if you dont want to use oauth, use token based authentication, here is a link to a tutorial https://scotch.io/tutorials/the-ins-and-outs-of-token-based-authentication – warrior Jul 29 '16 at 19:59
  • You don't need the Login from your controller. Take a look here: http://stackoverflow.com/questions/38661090/token-based-authentication-in-web-api-without-any-user-interface/38670221#38670221 –  Jul 30 '16 at 04:14

0 Answers0