python ruby-programming-language Smalltalk Vue.js Knockoutjs TypeScript JavaScript, OOPs JavaScript Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 4 Angular 2 AngularJs 1.x NodeJs Perl Programming R Programming RequireJs Rust Programming Backbonejs closure programming language go-programming-language kotlin-programming-language
ASP.NET MVC API Authentication and Authorization Filters

ASP.NET MVC API Authentication and Authorization Filters

ASP.NET Web API Security Filters -
1.     HTTP Module
2.     OWIN Middleware
3.     Message Handler
4.     Action Filter
5.     Authorization Filter
6.     Authentication Filter

The authentication filter is used to successfully authenticate the request and the authorization filter is used to successfully authorize the request. If successfully authenticate and authorize the requests, the controller action returns 200 (OK).

Authentication Filter Contains Two methods -
1 -Authenticate Sync Is use to authenticates the request by validating the credentials in the request, if present.
2 - Challenge SyncIs use to adds an authentication challenge to the HTTP response, if needed.

The flow in the Web API 2 Pipeline -



The authentication filters add a Www-Authenticate header to the response i.e.


Example - Implementing a Web API Authentication Filter
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
    //1. Look for credentials in the request.
    HttpRequestMessage request = context.Request;
    AuthenticationHeaderValue authorization = request.Headers.Authorization;

    //2. If there are no credentials, do nothing.
    if (authorization == null)
    {
        return;
    }

    //3. If there are credentials but the filter does not recognize the 
    //authentication scheme, do nothing.
    if (authorization.Scheme != "Basic")
    {
        return;
    }

    //4. If there are credentials that the filter understands, try to validate them.
    //5. If the credentials are bad, set the error result.
    if (String.IsNullOrEmpty(authorization.Parameter))
    {
        context.ErrorResult = new AuthenticationFailureResult("Missing credentials", request);
        return;
    }

    Tuple<string, string> userNameAndPasword = ExtractUserNameAndPassword(authorization.Parameter);
    if (userNameAndPasword == null)
    {
        context.ErrorResult = new AuthenticationFailureResult("Invalid credentials", request);
    }

    string userName = userNameAndPasword.Item1;
    string password = userNameAndPasword.Item2;

    IPrincipal principal = await AuthenticateAsync(userName, password, cancellationToken);
    if (principal == null)
    {
        context.ErrorResult = new AuthenticationFailureResult("Invalid username or password", request);
    }

    //6. If the credentials are valid, set principal.
    else
    {
        context.Principal = principal;
    }
}

Setting an Error Result-

public class AuthenticationFailureResult : IHttpActionResult
{
    public AuthenticationFailureResult(string reasonPhrase, HttpRequestMessage request)
    {
        ReasonPhrase = reasonPhrase;
        Request = request;
    }

    public string ReasonPhrase { get; private set; }

    public HttpRequestMessage Request { get; private set; }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        return Task.FromResult(Execute());
    }

    private HttpResponseMessage Execute()
    {
        HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
        response.RequestMessage = Request;
        response.ReasonPhrase = ReasonPhrase;
        return response;
    }
}

References-

I hope you are enjoying with this post! Please share with you friends. Thank you so much!
ANIL SINGH

Hi there! Welcome to my blog. My name is Anil Singh. I'm a author of this blog. For more detail about me, kindly refer to this link..
My Blogs - http://code-sample.com and http://code-sample.xyz
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like
www.code-sample.com/. Powered by Blogger.
ASK Questions