Web API Basic Authentication in MVC

Updated : Sep 01, 2019 in Asp.Net MVC

How to Authentication in Web API 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

Like
Like Love Haha Wow Sad Angry

Subscribe
Notify of
guest
4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Sergio Gushard
March 20, 2020 8:47 am

I really appreciate your help with my project!

Helaine Valladao
April 7, 2020 1:43 am

First time visiting your website, I love it!

Britt Livingood
April 14, 2020 3:46 pm

First time visiting your website, I enjoy your blog!

안전놀이터
안전놀이터
April 22, 2020 2:50 am

Best blog thanks for sharing!

4
0
Would love your thoughts, please comment.x
()
x