简体   繁体   中英

MVC 5 Web API - Use API Key

I am building a Web API using MVC 5 in C#.

I've seen a lot of sites use API Keys and would like to implement that in my code. I have a general idea on how to authenticate when a key IS passed and how to generate the keys...my question though is: Is there a way to have all of my post/put/delete class's use this authentication method without having to manually add it to all of them?

Are there any OOB solutions for this that would make this entire process easier?

I have googled away at this issue but feel I may be using incorrect terminology and that could be why I am not getting anywhere.

Thanks in advance for any help!

Essentially what you are asking for is the [Authorize] tag present in MVC, it will allow you to restrict access to authorized users and then further restrict to users in specific roles.

Really all you have to do is just add the tag, [Authorize], to any method you don't want anonymous users using. If you don't want them accessing a specific page just add authorize to your controller functions that return/handle the view. You can also set it up to use a whitelist and then only what you explicitly label as available will be available for anonymous (not logged in) users.

Article on MVC authentication:

http://msdn.microsoft.com/en-us/library/ff398049(v=vs.100).aspx

I'd recommend completely going through that walk through as it is pretty comprehensive and the examples are both accessible and easy to extrapolate from.

This MSDN site is a more technical break down of the authorize tag:

http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute(v=vs.118).aspx

A code sample from the article:

[Authorize]  
public class AccountController : Controller 
{
    public AccountController () { . . . }

    [AllowAnonymous]
    public ActionResult Register() { . . . }

    public ActionResult Manage() { . . . }

    public ActionResult LogOff() { . . . } . . . 
}

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