Thursday 6 August 2015

Authentication Filter

Authentication  is the process of accepting credentials from a user and validating those credentials.The user's identity is referred to as a principal. 

The client provides credentials. Server verifies the identity of the principal.

After the identity is known, the application may or may not authorize the principal to access resources on the system. 

PFB the defination of the interface:

public interface IAuthenticationFilter
{
       void OnAuthentication(AuthenticationContext filterContext);
      void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext);
}

  • The OnAuthentication method is executed first and can be used to perform any needed authentication.
  • The OnAuthenticationChallenge method is used to restrict access based upon the authenticated user's principal.
And we might customize the attribute,something like this:


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

        public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
        {
            var user = filterContext.HttpContext.User;
            if (user == null || !user.Identity.IsAuthenticated)
            {
                filterContext.Result = new HttpUnauthorizedResult();
            }
        }
    }

Now all you need to do is place this attribute over the controller class or individual methods

[CustomAuthAttribute]
....Your class or method ......

No comments:

Post a Comment