Token based authentication in Web API without any user interface

174,448

ASP.Net Web API has Authorization Server build-in already. You can see it inside Startup.cs when you create a new ASP.Net Web Application with Web API template.

OAuthOptions = new OAuthAuthorizationServerOptions
{
    TokenEndpointPath = new PathString("/Token"),
    Provider = new ApplicationOAuthProvider(PublicClientId),
    AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
    AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
    // In production mode set AllowInsecureHttp = false
    AllowInsecureHttp = true
};

All you have to do is to post URL encoded username and password inside query string.

/Token/userName=johndoe%40example.com&password=1234&grant_type=password

If you want to know more detail, you can watch User Registration and Login - Angular Front to Back with Web API by Deborah Kurata.

Share:
174,448
Souvik Ghosh
Author by

Souvik Ghosh

Updated on July 08, 2022

Comments

  • Souvik Ghosh
    Souvik Ghosh almost 2 years

    I am developing a REST API in ASP.Net Web API. My API will be only accessible via non-browser based clients. I need to implement security for my API so I decided to go with Token based authentication. I have a fair understanding of token based authentication and have read a few tutorials, but they all have some user interface for login. I don't need any UI for login as the login details will be passed by the client through HTTP POST which will be authorized from our database. How can I implement token based authentication in my API? Please note- my API will be accessed in high frequency so I also have to take care of performance. Please let me know if I can explain it any better.

  • Souvik Ghosh
    Souvik Ghosh almost 8 years
    So I will create a POST request to /TOKEN with username and password in the HTTP Header/Body? I will have username and hashed password for all the users in my app database. How should I implement this?
  • Win
    Win almost 8 years
    You need ASP.Net Identity (I believe you already have one). If not, create a ASP.Net Web API project and see the source code.
  • Monojit Sarkar
    Monojit Sarkar almost 8 years
    what is grant_type=password ? please share knowledge. thanks
  • frenchie
    frenchie over 5 years
    I think putting a username and password in the query string is a BAD BAD BAD idea.
  • Win
    Win over 5 years
    @frenchie grant_type=password is OAuth 2.0 - Resource Owner Password Credentials Grant Type. It is not something we see in browser's navigation bar.
  • Vikas Lalwani
    Vikas Lalwani almost 4 years
    Here is the complete step by step procedure to create OAuth token based authentication in C# using Web API : qawithexperts.com/article/api/…