Redirect user after authentication using OpenIdConnect in ASP.Net MVC

I am using the OpenIdConnect provider with Owin / Katana for authentication in my asp.net mvc application. OpenIdConnect Provides Active Directory user authentication. I wanted to do a simple authorization check after authenticating the user and redirecting the user to another view.

app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions()
        {
            Authority = "url",
            Scope="scopes",
            ResponseType = "response",
            ClientId = "clientid",
            SignInAsAuthenticationType = "Cookies",
            Notifications = new OpenIdConnectAuthenticationNotifications()
            {
                SecurityTokenValidated = (context) =>
                {
                    var identity = context.AuthenticationTicket.Identity;
                    var emailClaim = identity.Claims.Where(r => r.Type == ClaimTypes.Email).FirstOrDefault();

                    var user = dbContext.Users.Where(u=>u.Email==emailClaim.Value);
                    if (user != null)
                    {
                        //add user information to claims.
                        identity.AddClaim(new Claim(CustomClaimTypes.PersonId, user.Name.ToString()));
                    }
                    else
                    {
                        //redirect to a page 
                    }

                    return Task.FromResult(0);
                }
             }
        });

How to redirect a user if he is not in my database.

+4
source share
2 answers

, AuthorizeAttribute . custom authorize , , , .

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);
            }
        }
    }
}
0

, - , . , -

1

//redirect to a page 
context.AuthenticationTicket.Properties.RedirectUri = "Url";

2

//redirect to a page      
context.HandleResponse();
context.Response.Redirect("/Error?message=" + context.Exception.Message);

, , HttpContext.User.Identity . , HandlResponse . , .

+12

Source: https://habr.com/ru/post/1606650/


All Articles