Frage

I'm currently working on a ASP.NET MVC4 website. And in that website i wan't users that are part of an certain role to be allowed to run the code. I use the following code:

    [Authorize(Roles = GROUP)]
    public void Auth()
    {
        /* if user is in the domain and signed in
         * and a member of the above group 
         * they will come here */

        username = User.Identity.Name;

        //Do somthing
    }

And this works great, but when the user isn't part of the domain and/or group it wil prompt for username and password. Is it possible to skip the prompt and just redirect that user?

This website is setup in a IIS 8 with authentication set to windows authentication

War es hilfreich?

Lösung

Well I would create a Custom Authorization Attribute and implement HandleUnauthorizedRequest method to solve this problem.

public class CustomAutorizeAttribute : AuthorizeAttribute
{
   protected override bool AuthorizeCore(HttpContextBase httpContext)
   {
      // do authorization logic
      // ...


      return (/* isAuthorized */);
   }


   protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
   {
      UrlHelper urlHelper = new UrlHelper(filterContext.RequestContext);


      filterContext.Result = new RedirectResult(urlHelper.Action("Index", "Error"));
   }
}

For more information read How to: Create a Custom Authorization Attribute

Andere Tipps

use

 [Authorize(Roles = GROUP)]
  [HandleError(ExceptionType = typeof(UnauthorizedAccessException), View = "ApplicationError")]
    public void Auth()
    {
        /* if user is in the domain and signed in
         * and a member of the above group 
         * they will come here */

        username = User.Identity.Name;

        //Do somthing
    }

where you can sepcify view for unauthorized access user

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top