8

Sto sviluppando un'applicazione Internet MVC 5 e sto usando Identity 2.1.MVC 5 - Aggiungere un reclamo a un utente

Come posso aggiungere un claim a un utente, dopo che l'utente ha effettuato l'accesso, dove conosco lo username?

Ecco quello che ho:

public void AddClaimToUser(string userName, string type, string value) 
{ 
    var AuthenticationManager = HttpContext.Current.GetOwinContext().Authentication; 
    var Identity = new ClaimsIdentity(userName); 
    Identity.AddClaim(new Claim(type, value)); 
    AuthenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(Identity), new AuthenticationProperties { IsPersistent = true }); 
} 

Tuttavia, dopo che io chiamo questo metodo, e verifico rivendicazioni per l'utente, l'aggiunta claim non è elencato.

Ecco il codice che sto usando per ottenere i crediti in un controller:

var identity = (ClaimsIdentity)User.Identity; 
IEnumerable<Claim> claims = identity.Claims; 

Grazie in anticipo.

risposta

0

Non è sufficiente dare AuthenticationResponseGrant per aggiungere un reclamo all'utente già connesso. Devi ottenere l'identità, aggiungere un nuovo reclamo (lo fai già), quindi firmare l'utente e accedere di nuovo. Lo faccio praticamente in this answer

2

Prima di tutto devi creare un metodo per aggiungere un reclamo in IdentityModels.cs class.come questo, nel codice seguente ho creato un reclamo per CompanyId.

public class ApplicationUser : IdentityUser 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public bool IsActive { get; set; } 
    public int? CompanyId { get; set; } 


public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) 
{ 

    var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); 

    userIdentity.AddClaim(new Claim("CompanyId", (this.CompanyId + "" ?? "0"))); 

    return userIdentity; 
}} 

Dopo scrittura sopra il codice, è necessario scrivere più un metodo in IdentityConfig.cs

public static class IdentityExtensions{ 
public static int CompanyId(this IIdentity identity) 
{ 
return Convert.ToInt32(((ClaimsIdentity)identity).FindFirst("CompanyId").Value); 
}} 

Dopo questo si può ottenere il vostro reclamo creata in qualsiasi controller semplicemente digitando ..

int companyId = User.Identity.CompanyId();