What is the .NET Core equivalent of IAuthenticationFilter?

2.6k Views Asked by At

How can authentication be done in .NET Core as it was done using IAuthenticationFilter?

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

    void IAuthenticationFilter.OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)  
    {  
        if (filterContext.Result == null || filterContext.Result is HttpUnauthorizedResult)  
        {  
            filterContext.Result = new RedirectToRouteResult(  
                new RouteValueDictionary {  
                { "controller", "Account" },  
                { "action", "Login" } });  
        }  
    }  
}  

I am a newbie with .NET Core and filters. I was trying to authenticate users with filters before they can be allowed to access an action in a controller. Using this in .NET Core gives an error

"Error CS7069 Reference to type 'HttpContextBase' claims it is defined in 'System.Web', but it could not be found".

After searching this error I found that this is only available in .NET Framework. How do I do authentication with filters in .NET Core?

1

There are 1 best solutions below

0
Brando Zhang On

Asp.net core doesn't contain the IAuthenticationFilter, if you want to authenticated the user, I suggest you could try to refer to this article.

If you want to check the user's claim like roles before go to the controller, you could consider using the IAuthorizationFilter.

More details, you could refer to below codes:

public class CustomAuthorizationFilterAttribute : Attribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        string currentUserRole = Convert.ToString(context.HttpContext.Session.GetString("UserRole"));

        if (!string.IsNullOrEmpty(currentUserRole))
        {
            if (currentUserRole != "Admin")
            {
                context.Result = new RedirectToRouteResult
            (
            new RouteValueDictionary(new
            {
                action = "Error",
                controller = "Error"
            }));

            }
            else
            {
                context.Result = new RedirectToRouteResult
           (
           new RouteValueDictionary(new
           {
               action = "Error",
               controller = "Error"
           }));

            }
        }
        else
        {
            context.Result = new RedirectToRouteResult
            (
            new RouteValueDictionary(new
            {
                action = "Error",
                controller = "Error"
            }));

        }
    }
}