Ashkan Hovold
Ashkan Hovold

Reputation: 908

Override redirecturl when not authorized .net core

Basicly what I want to accomplish is something like this:

[AllowAnonymous]
    public ActionResult MyAction(string id)
    {
        if (Request.IsAuthenticated)
        {
            //do stuff
            return View();
        }
        //if we come here, redirect to my custom action
        return RedirectToAction("Action","Controller", new {@id=id});
    } 

But instead of this approach I'm trying to find out if it's possible to do the same thing with a custom attribute, looking something like this:

[Authorize(RedirectIfNotAuthorized="~/Controller/Action/id")]
    public ActionResult MyAction(string id)
    {

        //do stuff
        return View();
    } 

From what I've read it is possible to change the default url ("/Account/Login") to another url by changing the configuration for Asp.net Identity. This is not what I want. I want in some specific cases to redirect to another url.

(Backstory to this is that in some cases when a user is logged out due to inactivity some redirect urls are not wanted. Lets say a user was about to download a file from a url like ("~/Files/Pdf/123") but gets logged out. I do not wish for the user to get redirected to this url when he logs back in).

Upvotes: 3

Views: 1077

Answers (1)

ingvar
ingvar

Reputation: 4375

You need custom attribute:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Attributes
{
    public class AuthAttribute : ActionFilterAttribute
    {
        private readonly string _action;
        private readonly string _controller;
        private readonly string _role;

        public AuthAttribute(string action, string controller, string role)
        {
            _action = action;
            _controller = controller;
            _role = role;
        }

        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            if (!filterContext.HttpContext.User.IsInRole(_role))
            {
                filterContext.Result = new RedirectToRouteResult(new {action = _action, controller = _controller});
            }
            else
            {
                base.OnResultExecuting(filterContext);
            }
        }
    }
}

Usage:

[Auth("Test", "Home", "Admin")]
public IActionResult Index()

Upvotes: 3

Related Questions