Custom Authentication in ASP.NET MVC

Views: 79
Comments: 0
Like/Unlike: 1
Posted On: 03-Aug-2019 00:59 

Share:   fb twitter linkedin
Brian
Participant
20 Points
9 Posts

Intoduction

In this article, we will discuss how to create a Custom Authentication Filter in ASP.Net MVC application. The Authentication Filter was introduced with MVC 5 and provides a great enhancement for authenticating a user.

Earlier, beofre MVC 5, we were used two built-in filters i.e. Authorize and AllowAnonymous. The Authorize filter performs the authorization tasks for an authenticated user. The AllowAnonymous filter enables anonymous users to access certain Controllers/Actions. In this way, we were protect the entire application by using the Authorize and AllowAnonymous attribute.

But now, we can isolate the Authentication related tasks to a new custom authentication filter and perform the authorization related tasks using the authorization filters only.

How to create a Custom Authentication Filter in MVC?

We can create a Custom Authentication filter in MVC by creating a class by implementing the IAuthenticationFilter Interface. This IAuthenticationFilter interface has two methods. Following is the class definition of IAuthenticationFilter interface.

public class CustomAuthenticationAttribute : ActionFilterAttribute, IAuthenticationFilter
{
    public void OnAuthentication(AuthenticationContext filterContext)
    {

    }

    public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
    {
        if (filterContext.Result == null || filterContext.Result is HttpUnauthorizedResult)
        {

        }
    }
}

OnAuthentication:
This method is used to authenticate the request by user. The AuthenticationContext param provides us the necessary information which is required for performing authentication. We can use this information to authentication decisions based on the current context.

OnAuthenticationChallenge:
This Method gets called when Authentication or Authorization is failed and get called after the execution of action method but before rendering the view.

Example

Let's consider a case in which we want to check session for UserId key. And if request is no authenticate redirect to /UnAuthorize page with custom message.

public class CustomAuthenticationAttribute : ActionFilterAttribute, IAuthenticationFilter
{
    public void OnAuthentication(AuthenticationContext filterContext)
    {
        if (string.IsNullOrEmpty(Convert.ToString(filterContext.HttpContext.Session["UserId"])))
        {
            filterContext.Result = new HttpUnauthorizedResult();
        }
    }

    public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
    {
        if (filterContext.Result == null || filterContext.Result is HttpUnauthorizedResult)
        {
            var tempDataDictionary = GetTempDataDictionary(filterContext);

            filterContext.Controller.TempData = GetTempDataDictionary(filterContext);
            filterContext.Result = new RedirectResult("/UnAuthorize");
        }
    }

    private TempDataDictionary GetTempDataDictionary(AuthenticationChallengeContext filterContext)
    {
        var actionName = filterContext.ActionDescriptor.ActionName;
        var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
        var httpMethod = filterContext.RequestContext.HttpContext.Request.RequestType;
        var RedirectURL = filterContext.RequestContext.HttpContext.Request.RawUrl;

        var tempDataDictionary = new TempDataDictionary();
        tempDataDictionary.Add("RedirectURL", RedirectURL);
        tempDataDictionary.Add("ErrorMessage", actionName.ToLower() + ":" + controllerName.ToLower());

        return tempDataDictionary;
    }
}

How to use at Action?

Now, you decorate as an attribute at action method:

[CustomAuthentication()]
public ActionResult AboutUs()
{

}

Conclusion

In this article, we try to understand how to create a Custom Authentication filter in MVC application with a simple example. I hope will be helpful for you.

0 Comments
  
 Log In to Chat