Web API Basic Authentication in MVC

Updated : Sep 01, 2019 in Asp.Net MVC

Web API authentication example

in this article well discuss the web API authentication example and what is web API, check the web APIs by using postman

Introduction Web API authentication :

The Web API is an extensible framework for building HTTP based services requests.

we will access different types of applications such as web applications, windows applications, mobile apps, etc.

It works more or less the same way as It is like web services or WCF service but it only supports HTTP protocol.

Web API Basic Authentication in MVC
Web API Basic Authentication in MVC
Web API authentication example
Step 1:

Add a class name like “WebApiAuthenticationAttribute”,it will be used as an Authorization filter. The class  WebApiAuthenticationAttribute inherits from AuthorizationFilterAttribute

 Authentication in MVC
Authentication in MVC
public class WebApiAuthenticationAttribute : AuthorizationFilterAttribute
    {
        // It contains an override method OnAuthorization()
    }
Step 2:
validate a user from Method

Add a  method called  “IsAuthorizedUser” this method will take two parameters (string username, string password)  username and password.

It will check the username and password with the database value if it succeeds it returns Bool value as true otherwise it will return false.

WebApiAuthenticationAttribute  class contains an override method OnAuthorization(),it will performs all the validations

 public class WebApiAuthenticationAttribute : AuthorizationFilterAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (actionContext.Request.Headers.Authorization != null)
            {
                var authToken = actionContext.Request.Headers
                    .Authorization.Parameter;

                //decode value in 'Username:Password' format
                var decodeauthToken = System.Text.Encoding.UTF8.GetString(
                    Convert.FromBase64String(authToken));

                // spliting using ':' 
                var arrUserNameandPassword = decodeauthToken.Split(':');

                
                if (IsAuthorizedUser(arrUserNameandPassword[0], arrUserNameandPassword[1]))
                {
                    // setting current principle
                    Thread.CurrentPrincipal = new GenericPrincipal(
                    new GenericIdentity(arrUserNameandPassword[0]), null);
                }
                else
                {
                    actionContext.Response = actionContext.Request
                    .CreateResponse(HttpStatusCode.Unauthorized);
                }
            }
            else
            {
                actionContext.Response = actionContext.Request
                 .CreateResponse(HttpStatusCode.Unauthorized);
            }
        }

        public static bool IsAuthorizedUser(string Username, string Password)
        {
            // In this method we can handle our database logic here...
            return Username == "vijay" && Password == "123";
        }

    }
Step 3:

Authorization filter we need to register it. You can register at a global level, controller level or action level. In this example, we have added the controller level.

        [WebApiAuthenticationAttribute]
        [HttpGet]
        [Route("api/WebApi/Jsondata")]
        public IHttpActionResult Jsondata()
        {
           //some logic
        }

Step:4

We have to install a postman for Checking the web API authentication example. for Post Man click Link

postman for Checking the Web API
postman for Checking the WebAPI

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *