Babu James
Babu James

Reputation: 2843

ASP.NET MVC 5 OWIN Area Authentication

I am building an ASP.NET MVC 5 based web site that uses OWIN based authentication. I have created a new Area in the application for administrator panel. I would like to have a different login page than that of the normal user.

For instance, when i go to http://site/admin/home/index it should check for authorization and redirect to http://site/admin/account/login instead of going to site user login page.

I have already tried implementing a custom Authorize attribute. However, I somehow feel that it's not the right approach.

Could someone suggest a better or more right solution for this?

Edit: Custom attribute implementation

public class AuthorizeAreaAttribute : AuthorizeAttribute
{
    public string Url { get; set; }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            filterContext.HttpContext.Response.Redirect(Url);
            filterContext.HttpContext.Response.End();
        }
        base.OnAuthorization(filterContext);
    }
}

Upvotes: 3

Views: 2143

Answers (1)

Mohsen Esmailpour
Mohsen Esmailpour

Reputation: 11544

In Configuration method in App_Start/Startup.Auth.cs file you can change redirect behavoir.

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        // Enables the application to validate the security stamp when the user logs in.
        // This is a security feature which is used when you change a password or add an external login to your account.
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, User>(
            validateInterval: TimeSpan.FromMinutes(30),
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)
        ),

        // Change redirect
        OnApplyRedirect = ApplyRedirect
    }
});

private static void ApplyRedirect(CookieApplyRedirectContext context) 
{
    Uri absoluteUri;
    PathString ContentVersioningUrlSegments = PathString.FromUriComponent("/admin/");

    if (Uri.TryCreate(context.RedirectUri, UriKind.Absolute, out absoluteUri)) 
    {
        PathString remainingPath;
        var path = PathString.FromUriComponent(absoluteUri);
        if (path.StartsWithSegments(ContentVersioningUrlSegments, out remainingPath) && remainingPath.HasValue && remainingPath.Value.Length > 1))
                context.RedirectUri = "url" +
                    new QueryString(
                        context.Options.ReturnUrlParameter,
                        context.Request.Uri.AbsoluteUri);
    }

    context.Response.Redirect(context.RedirectUri);
}

Upvotes: 2

Related Questions