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?
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: