use*_*783 5 c# owin asp.net-mvc-5 openid-connect identityserver3
我正在使用OpenIdConnect提供程序与Owin/Katana在我的asp.net mvc应用程序中进行身份验证.OpenIdConnect Provide针对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);
}
}
});
Run Code Online (Sandbox Code Playgroud)
如果用户不在我的数据库中,如何重定向用户.
maj*_*ita 19
添加到接受的答案,以防有人像我一样与此战斗.我发现以下选项对我有用 -
选项1
//redirect to a page
context.AuthenticationTicket.Properties.RedirectUri = "Url";
Run Code Online (Sandbox Code Playgroud)
选项2
//redirect to a page
context.HandleResponse();
context.Response.Redirect("/Error?message=" + context.Exception.Message);
Run Code Online (Sandbox Code Playgroud)
请注意,第二个选项导致我的HttpContext.User.Identity为null.我想因为HandlResponse停止了所有处理.如果不是一个问题,仍然有用.
我可以通过编写自定义 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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6778 次 |
最近记录: |