Redirect user after authentication with OpenIdConnect in ASP.Net MVC

后端 未结 2 1424
北恋
北恋 2021-01-05 06:31

I am using OpenIdConnect provider with Owin/Katana for authentication in my asp.net mvc application. OpenIdConnect Provide authenticates users against Active Directory. I wa

2条回答
  •  半阙折子戏
    2021-01-05 07:00

    I was able to achieve this by writing custom AuthorizeAttribute and using it on every class in my application. In the custom authorize attribute I am checking for the a Claim which will be available if the authorization check is successful and redirecting the user to a separate view if not authorized.

    public class CustomAuthorize : AuthorizeAttribute
    {
        public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
    
            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                if(UserClaims.PersonId == 0)
                {
                    UrlHelper helper = new UrlHelper(filterContext.RequestContext);
    
                    string url = helper.Action("Unauthorized","Error",null,filterContext.HttpContext.Request.Url.Scheme);
    
                    filterContext.Result = new RedirectResult(url);
                }
            }
        }
    }
    

提交回复
热议问题