Подтвердить что ты не робот

Как добавить претензии в ASP.NET Identity

Я пытаюсь найти документ или пример того, как добавить пользовательские требования к идентификатору пользователя в MVC 5 с помощью ASP.NET Identity. В этом примере следует указать, куда вставлять претензии в конвейер безопасности OWIN и как их перенести в cookie с использованием проверки подлинности на основе форм.

4b9b3361

Ответ 1

Возможно, следующая статья может помочь:

var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, "Brock"));
claims.Add(new Claim(ClaimTypes.Email, "[email protected]"));
var id = new ClaimsIdentity(claims,DefaultAuthenticationTypes.ApplicationCookie);

var ctx = Request.GetOwinContext();
var authenticationManager = ctx.Authentication;
authenticationManager.SignIn(id);

Ответ 2

Правильное место для добавления претензий при условии, что вы используете шаблон проекта ASP.NET MVC 5, находится в ApplicationUser.cs. Просто найдите Add custom user claims here. Это приведет вас к методу GenerateUserIdentityAsync. Это метод, который вызывается, когда система идентификации ASP.NET извлекает объект ApplicationUser и должна превратить это в свойство ClaimsIdentity. Вы увидите эту строку кода:

// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

После этого будет комментарий:

// Add custom user claims here

И, наконец, он возвращает идентификатор:

return userIdentity;

Итак, если вы хотите добавить пользовательскую заявку, ваш GenerateUserIdentityAsync может выглядеть примерно так:

// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

// Add custom user claims here
userIdentity.AddClaim(new Claim("myCustomClaim", "value of claim"));

return userIdentity;

Ответ 3

Если вы хотите добавить пользовательские претензии во время регистрации, этот код будет работать:

            var user = new ApplicationUser
            {
                UserName = model.UserName,
                Email = model.Email
            };
            var result = await UserManager.CreateAsync(user, model.Password);
            // Associate the role with the new user 
            await UserManager.AddToRoleAsync(user.Id, model.UserRole);
            // Create customized claim 
            await UserManager.AddClaimAsync(user.Id, new Claim("newCustomClaim", "claimValue"));
            if (result.Succeeded)
            {...etc

Ответ 4

Вы можете сделать следующее в WEB API С#

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));
        identity.AddClaim(new Claim("Empresa", user.Empresa));
        identity.AddClaim(new Claim("ConnectionStringsName", user.ConnectionStringsName));

....