跨请求保留新声明



如何添加新声明,使它们在请求中持续存在,直到 cookie 过期?

我正在使用 OWIN 中间件、本地身份验证来验证登录系统的用户。

登录部分成功,我将角色添加到 ws 联合身份验证提供的用户声明中,以帮助授权用户使用某些操作方法。 在登录时,在控制器中,我编写了以下内容来添加角色:

string[] roles = { "Role1", "Role2" };
var identity = new ClaimsIdentity(User.Identity);
foreach (var role in roles)
{
identity.AddClaim(new Claim(ClaimTypes.Role, role));
}
var authenticationManager = HttpContext.GetOwinContext().Authentication;
authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant
(new ClaimsPrincipal(identity),
new AuthenticationProperties { IsPersistent = true });

但是,当我在下一个请求中检查声明时,我看不到角色声明。

身份验证成功后,我相信您添加了自定义声明(通常在成功进行身份验证后添加到某些事件处理程序)。现在,为了在后续请求中保留该信息,您需要在管道中的身份验证之前使用 CookieAuthentication 中间件。

工作原理 :

首次成功进行身份验证并添加自定义声明后,声明将转换为某种身份验证 cookie 并发送回客户端。后续请求将携带此身份验证 cookie。查找身份验证 cookie 的 Cookie 身份验证中间件将设置您的 Thread.CurrentPriciple 与从 cookie 获得的声明。

在第一次请求期间,当 cookie 中间件确实看到任何身份验证 cookie 时,它会将请求传递给管道线中的下一个中间件(在您的情况下是身份验证 owin)以质询用户登录。

app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationType = "Cookies",
AuthenticationMode= AuthenticationMode.Active,
CookieName="XXXXX",
CookieDomain= _cookiedomain,
/* you can go with default cookie encryption also */
TicketDataFormat = new TicketDataFormat(_x509DataProtector),
SlidingExpiration = true,
CookieSecure = CookieSecureOption.Always,
});

app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
ClientId = _clientID,
Authority = _authority,
RedirectUri = _redirectUri,
UseTokenLifetime = false,
Notifications = new OpenIdConnectAuthenticationNotifications
{
SecurityTokenValidated = SecurityTokenValidated,
AuthenticationFailed = (context) =>
{
/* your logic to handle failure*/
}
},
TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
{
ValidIssuers = _validIssuers,
ValidateIssuer = _isValidIssuers,
}
});

编辑:(附加信息)
几乎上面的确切代码也适用于ws联盟,具有相同的逻辑和所有内容。

SecurityTokenValidated = notification =>
{
ClaimsIdentity identity = notification.AuthenticationTicket.Identity;
string[] roles = { "Role1", "Role2" };
foreach (var role in roles)
{
identity.AddClaim(new Claim(ClaimTypes.Role, role));
}
return Task.FromResult(0);
}

您需要使用与Startup.ConfigureAuth中使用的相同AuthenticationType。例如:

Startup.ConfigureAuth

app.UseCookieAuthentication(new CookieAuthenticationOptions {
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
//....
});

在您的登录代码中(在问题中提供):

var identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie);

或者确保User.Identity具有相同的AuthenticationType,并且您可以像以前一样使用它:

var identity = new ClaimsIdentity(User.Identity);

现在重要的部分是,对于登录,您应该在唱歌之前添加声明,而不是之后。像这样:

HttpContext.GetOwinContext().Authentication.SignIn(identity);

您可以在登录后添加声明,但您将在创建 cookie 后立即对其进行修改,这效率不高。如果在其他代码中需要修改声明,则可以使用类似于代码的内容,但必须从Current获取上下文:

HttpContext.Current.GetOwinContext().Authentication.AuthenticationResponseGrant =
new AuthenticationResponseGrant(new ClaimsPrincipal(identity),
new AuthenticationProperties { IsPersistent = true });

因此,您可以通过简单地添加Current来修复代码,例如上面,但这对登录代码没有效率,最好将声明传递给SignIn函数。

你可以在WEB API C # (SOAP),(存储过程)中执行以下操作

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
LoginModel model = new LoginModel();
//validate user credentials and obtain user roles (return List Roles) 
//validar las credenciales de usuario y obtener roles de usuario
var user = model.User = _serviceUsuario.ObtenerUsuario(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "El nombre de usuario o la contraseña no son correctos.cod 01");
return;
}
var stringRoles = user.Roles.Replace(" ", "");//It depends on how you bring them from your DB
string[] roles = stringRoles.Split(',');//It depends on how you bring them from your DB
var identity = new ClaimsIdentity(context.Options.AuthenticationType);          
foreach(var Rol in roles)
{
identity.AddClaim(new Claim(ClaimTypes.Role, Rol));
}
identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
identity.AddClaim(new Claim(ClaimTypes.Email, user.Correo));
identity.AddClaim(new Claim(ClaimTypes.MobilePhone, user.Celular));
identity.AddClaim(new Claim("FullName", user.FullName));//new ClaimTypes
identity.AddClaim(new Claim("Empresa", user.Empresa));//new ClaimTypes
identity.AddClaim(new Claim("ConnectionStringsName", user.ConnectionStringsName));//new ClaimTypes
//add user information for the client
var properties = new AuthenticationProperties(new Dictionary<string, string>
{
{ "userName",user.NombreUsuario },
{ "FullName",user.FullName },
{ "EmpresaName",user.Empresa }
});
//end
var ticket = new AuthenticationTicket(identity, properties);
context.Validated(ticket);
}

最新更新