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.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
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.
All you have to do is to post URL encoded username and password inside query string.
If you want to know more detail, you can watch User Registration and Login - Angular Front to Back with Web API by Deborah Kurata.
I think there is some confusion about the difference between MVC and Web Api. In short, for MVC you can use a login form and create a session using cookies. For Web Api there is no session. That's why you want to use the token.
You do not need a login form. The Token endpoint is all you need. Like Win described you'll send the credentials to the token endpoint where it is handled.
Here's some client side C# code to get a token:
In order to use the token add it to the header of the request:
Where Token is:
Now for the server side:
In Startup.Auth.cs
And in ApplicationOAuthProvider.cs the code that actually grants or denies access:
As you can see there is no controller involved in retrieving the token. In fact, you can remove all MVC references if you want a Web Api only. I have simplified the server side code to make it more readable. You can add code to upgrade the security.
Make sure you use SSL only. Implement the RequireHttpsAttribute to force this.
You can use the Authorize / AllowAnonymous attributes to secure your Web Api. Additionally you can add filters (like RequireHttpsAttribute) to make your Web Api more secure. I hope this helps.