In order to implement Role Based Basic Authentication, we will have two classes.  One for Authenticate and another for Auhorize. Follow the code. You might have to added required references.

 

BasicAuthenticationAttribute.cs

using Repository;

using Repository.Shared;

using System;

using System.Net;

using System.Security.Claims;

using System.Security.Principal;

using System.Text;

using System.Threading;

using System.Web;

using System.Web.Http;

using System.Web.Http.Controllers;

using System.Web.Http.Filters;

 

namespace BusinessLogic

{

    public class BasicAuthenticationAttribute : AuthorizationFilterAttribute

    {

        private IUnitOfWork unitOfWork = new UnitOfWork();

        public override void OnAuthorization(HttpActionContext actionContext)

        {

            if (actionContext.Request.Headers.Authorization == null)

            {

                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);

            }

            else

            {

                // Gets header parameters  

                string authenticationString = actionContext.Request.Headers.Authorization.Parameter;

                string originalString = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationString));

 

                // Gets username and password  

                string username = originalString.Split(':')[0];

                string password = originalString.Split(':')[1];

 

                // Validate username and password  

                var account = new AccountsLogic(unitOfWork).GetAccountByUser(username,password);

                if (account==null)

                {

                    // returns unauthorized error  

                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);

                }

                else if(account.Is_active.HasValue && account.Is_active.Value == false)

                {

                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);

                }

                else if (account.Is_active.HasValue && account.Is_active.Value == true)

                {

                    var identity = new GenericIdentity(username);

                    identity.AddClaim(new Claim(ClaimTypes.Name, account.Username));

                    identity.AddClaim(new Claim("ID", Convert.ToString(account.Id)));

                    IPrincipal principal = new GenericPrincipal(identity, account.UserType.Split(','));

                    Thread.CurrentPrincipal = principal;

                    if (HttpContext.Current != null)

                    {

                        HttpContext.Current.User = principal;

                    }

                }

                else

                {

                    actionContext.Response = actionContext.Request

                        .CreateResponse(HttpStatusCode.Unauthorized);

                }

            

            }

            base.OnAuthorization(actionContext);

        }

    }

}

 

AuthorizeUserRole.cs

using System.Web;
 
namespace BusinessLogic
{
    public class AuthorizeUserRole: System.Web.Http.AuthorizeAttribute
    {
        // 401 (Unauthorized) - indicates that the request has not been applied because it lacks valid 
        // authentication credentials for the target resource.
        // 403 (Forbidden) - when the user is authenticated but isn’t authorized to perform the requested 
        // operation on the given resource.
        protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
            {
                base.HandleUnauthorizedRequest(actionContext);
            }
            else
            {
                actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Forbidden);
            }
        }
    }
}

At Controller, you can either call it in attributes at the top of controller or at the top of action as required.

[BasicAuthentication]

[RoutePrefix("api/stocks")]

public class StocksController : ApiController

{

      [AuthorizeUserRole(Roles = "Admin,Retailer")]

        [Route("")]

        [HttpPost]

        public Stock AddStocks(Stock stock)

        {

            return new StocksBusiness(unitOfWork).SaveStocks(stock);

        }

}

blog comments powered by Disqus