我正在Owin / Katana中使用OpenIdConnect提供程序在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);
}
}
});
如果该用户不在我的数据库中,该如何重定向该用户。
通过编写自定义AuthorizeAttribute并将其用于应用程序中的每个类,我能够实现这一目标。在自定义授权属性中,我正在检查Claim,如果授权检查成功,该索赔将可用;如果未授权,则将用户重定向到单独的视图。
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);
}
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句