asp.net mvc basic authentication in web api

asp.net mvc basic authentication in web api
in this article, i will show you asp.net mvc basic authentication in web api

step: 1 create folder (Auth)

step: 2 create class on folder (BasicAuth)

step: 3 write below line of code:

public class BasicAuth : AuthorizationFilterAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        try
        {
            if (actionContext.Request.Headers.Authorization != null)
            {
                //taking the parameter from the header
                var authToken = actionContext.Request.Headers.Authorization.Parameter;
                //decode the parameter
                var decoAuthToken = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(authToken));
                //split by colon : and store in variable
                var UserNameAndPassword = decoAuthToken.Split(':');
                //Passing to a function for authorization
                if (IsAuthorizedUser(UserNameAndPassword[0], UserNameAndPassword[1]))
                {
                    // setting current principle
                    Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(UserNameAndPassword[0]), null);
                }
                else
                {
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                }
            }
            else
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
            }
        }
        catch (Exception ex)
        {
            ex.Message.ToString();
        }
    }
    public static bool IsAuthorizedUser(string Username, string Password)
    {
        // In this method we can handle our database logic here...
        //Here we have given the hard-coded values 
        return Username == "ajayvishu" && Password == "abc123";
    }
}

ste:4 add attribute on action method level like below example:

[Auth.BasicAuth]
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

Post a Comment

0 Comments