Background

I have a Web API 2 project, without any extension of ASP.NET MVC or ASP.NET projects. The API will only be used to communicate between the server and Windows 8, Windows Phone 8.1 and iOS applications. No website will consume the API. The API makes it possible for a user to manage products in a warehouse. A user can add, remove, and check products ín the database.

public class User
{
    public int Id { get; set; }
    [Required]
    public string UserName { get; set; }
    [Required]
    public string DisplayName{ get; set; }
    [Required]
    public bool IsEnabled {get; set;}
}

Nothing fancy - just a model for Entitiy Framework. Of course a model for the product also exists. Notice, I don't require any password from my users, since this is not important for the data security. The users of the API will never know each others UserName - only each others DisplayName.

The problems

The problem is regarding security in Web API. I do not want to expose my API to the whole world - just the applications. So i have done a lot research, and from the research I have the following to scenario:

Scenario #1

The best way to ensure a high level of security in my API is to:

  • Use SSL
  • Use token-based authentication of the clients
  • use a token with a very short expiration time
  • not to use the ASP.NET Identity
  • to use Message Handlers instead of Action Filters
  • Add a UserToken field to User model and generate a token for each user

Scenario #2

The best way to ensure a high level of security in my API is to:

  • use SSL
  • use ASP.NET Identity to do username and password approach
  • use a token-based approach based on the authentication of ASP.NET Identity

The Questions

  • What is the best approach? Scenario #1 or #2?
  • In general, what is the best way to secure an API?
  • Is the best way one of my scenarios?

Please feel free to add/remove items from the two scenarios, but also to add new and more secure scenarios.

有帮助吗?

解决方案

I would vote in favor #1, because I find it slightly easier to understand what's going on and control the behavior. We used this approach to build a fairly large enterprisey apps without too much fuss. It also is easily customizable, if needed (e.g. would 1 token per user suffice? Would you need multiple token if user simultaneously logs in from multiple devices?). However, it depends - as always. Both are totally viable approaches, so basically whatever you're more comfortable with, if it has all the features you need when another one doesn't.

In our case #1 was easier to implement and covered all our needs, your case might be different... or not.

许可以下: CC-BY-SA归因
scroll top