Kiran B
Kiran B

Reputation: 715

Add authorization to a specific route without adding attribute in mvc

I need to add authorization to a particular route without adding Authorize attribute. Is there any way I can do this in startup? I know I can add Authorize attribute globally to all the routes, but I need to add authorize just to a specific method in a controller without touching any code in that controller.

Upvotes: 2

Views: 1390

Answers (1)

svoychik
svoychik

Reputation: 1327

If you cannot touch code I see the only solution - check using middleware. Lets imagine that route you want to restrict access is POST '/users/register', so you can use ActionFilter registered globally in startup in which you check url and if its url is '/users/register' you are trying to check token and if token is not valid - return 401.

Also you can use Owin middleware

Here is simple example of implementation such logic using ActionFilter

public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            GlobalConfiguration.Configuration.Filters.Add(new CheckAuthorizationFilterAttribute());
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }
    }
    public class CheckAuthorizationFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var requestUri = actionContext.Request.RequestUri.AbsolutePath;
            if (requestUri == "/api/users/register")
            {
                var isTokenValid = ValidateToken();
                if (!isTokenValid)
                    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                return;
            }
        }

        public bool ValidateToken() => false;

        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {

        }
    }

Upvotes: 5

Related Questions