简体   繁体   中英

ASP.NET WebApi v2 - Securing with BasicAuthentication

I'm studying how to secure ASP.NET Web Api applications. I've started with Basic Authentication (yes - I know it's not recommended, yes - My final plan is to use Token Based Authentication. But I need to first learn and understand the basics).

At first, what I did was to create an Attribute that inherits from AuthorizeAttribute and use is on the controller I want to secure. It's very basic (and working):

public class SimpleUserNamePasswordAuthorizeAttribute : AuthorizeAttribute
{
    public string UserName { get; set; }
    public string Password { get; set; }

    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        string query = actionContext.Request.RequestUri.Query;
        var nvc = HttpUtility.ParseQueryString(query);
        string securityQueryToken = nvc["_auth"];


        if (string.IsNullOrEmpty(securityQueryToken) &&   actionContext.Request.Headers.Authorization == null)
        {
            return false;
        }
        string authToken = "";

        if (actionContext.Request.Headers.Authorization != null)
            authToken = actionContext.Request.Headers.Authorization.Parameter;
        else
            authToken = securityQueryToken;

        if (string.IsNullOrWhiteSpace(authToken))
        {
            return false;
        }
        // Decode the token from BASE64
        string decodedToken = Encoding.UTF8.GetString(Convert.FromBase64String(authToken));
        if(string.IsNullOrWhiteSpace(decodedToken))
        {
            return false;
        }
        // Extract username and password from decoded token
        int index = decodedToken.IndexOf(":", StringComparison.Ordinal);
        if(index == -1)
        {
            return false;
        }
        string userName = decodedToken.Substring(0, decodedToken.IndexOf(":", StringComparison.Ordinal));
        string password = decodedToken.Substring(decodedToken.IndexOf(":", StringComparison.Ordinal) + 1);
        return ((userName == UserName) && (password == Password));
    }
}

I read somewhere that this way of working is more common for for Web Api v1. And found this project that implements Basic Authentication: https://github.com/IdentityModel/IdentityModel.Owin.BasicAuthentication

From that I learned that they are using a different approach (that seems more correct) that I don't need my own Attribute , and use the [Authorize] that is part of ASP.NET.

They do that by inheriting AuthenticationHandler and AuthenticationMiddleware and using it as an Owin middleware. At first it didn't work until I removed the following from my WebApiConfig.cs in the App_Start directory:

config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

I also notice that it's being called on every request to the server, while with my own attribute calls are made only to relevant controller that uses my attribute.

  1. I'm wondering, what is the difference between the 2 approaches, and which is more "correct" way to use? Which gives better security?
  2. Why did I have to remove those lines from WebApiConfig.cs so it could work?
  3. Does the second method have some performance impact that the first method doesn't have?

2: Why did I have to remove those lines from WebApiConfig.cs so it could work?

By removing those lines it suppress of the host's default authentication mechanism (ie working of [Authroize] attribute) and enables your custom filter authentication mechanism.

1: I'm wondering, what is the difference between the 2 approaches, and which is more "correct" way to use? Which gives better security?

Using the Asp.net [Authorize] provides the default functionality of authentication by asp.net but by inheriting the AuthorizeAttribute gives you extensibility of writing your own functionality. While both gives you security it's up to you to decide which suits the best to you.

3: Does the second method have some performance impact that the first method doesn't have?

Don't have any technical idea, but it shouldn't have the performance impact.

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