【问题标题】:Redirect user after authentication with OpenIdConnect in ASP.Net MVC在 ASP.Net MVC 中使用 OpenIdConnect 进行身份验证后重定向用户
【发布时间】:2015-09-09 20:00:56
【问题描述】:

我在我的 asp.net mvc 应用程序中使用 OpenIdConnect 提供程序和 Owin/Katana 进行身份验证。 OpenIdConnect 提供针对 Active Directory 对用户进行身份验证。一旦用户通过身份验证并将用户重定向到另一个视图,我想进行简单的授权检查。

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

如果用户不在我的数据库中,我如何重定向用户。

【问题讨论】:

  • 我终于能够使用自定义 Authorize 属性来实现这一点。
  • 能否请您更详细地回答您自己的问题,并将其标记为答案?
  • 当然,刚刚发布了我的答案@pashute。谢谢

标签: c# asp.net-mvc-5 owin openid-connect identityserver3


【解决方案1】:

添加到已接受的答案中,以防有人像我一样与之抗争。我发现以下选项对我有用 -

选项 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 停止了所有处理。如果这不是问题,仍然有用。

【讨论】:

  • 选项 1 很好很干净
  • 选项 1 是我一直在寻找的,因为我希望用户登录并重定向。
【解决方案2】:

我可以通过编写自定义 AuthorizeAttribute 并在我的应用程序中的每个类上使用它来实现这一点。在自定义授权属性中,我正在检查一个声明,如果授权检查成功,它将可用,如果未授权,则将用户重定向到单独的视图。

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

【讨论】:

    猜你喜欢
    • 2019-11-23
    • 2015-04-20
    • 1970-01-01
    • 2019-01-27
    • 2010-11-27
    • 1970-01-01
    • 2017-08-19
    • 2013-02-14
    • 1970-01-01
    相关资源
    最近更新 更多