2016-05-30 2 views
3

Я переношу версию .NET 4.6 в .NET Core RC2 и задаюсь вопросом, как это сделать в .NET Core RC2.Претензии к signin в .NET Core RC2

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) 
{ 
     // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType 
     var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); 
     userIdentity.AddClaim(new Claim("FullName", string.Format("{0} {1}", this.Firstname, this.Lastname))); 
     userIdentity.AddClaim(new Claim("Organization", this.Organization.Name)); 
     userIdentity.AddClaim(new Claim("Role", manager.GetRoles(this.Id).FirstOrDefault())); 
     userIdentity.AddClaim(new Claim("ProfileImage", this.ProfileImageUrl)); 
     // Add custom user claims here 
     return userIdentity; 
} 

, а затем метод расширения для удостоверения личности.

public static class IdentityExtensions 
{ 
    public static string FullName(this IIdentity identity) 
    { 
     var claim = ((ClaimsIdentity)identity).FindFirst("FullName"); 
     // Test for null to avoid issues during local testing 
     return (claim != null) ? claim.Value : string.Empty; 
    } 

    public static string Organization(this IIdentity identity) 
    { 
     var claim = ((ClaimsIdentity)identity).FindFirst("Organization"); 
     // Test for null to avoid issues during local testing 
     return (claim != null) ? claim.Value : string.Empty; 
    } 

    public static string Role(this IIdentity identity) 
    { 
     var claim = ((ClaimsIdentity)identity).FindFirst("Role"); 
     // Test for null to avoid issues during local testing 
     return (claim != null) ? claim.Value : string.Empty; 
    } 

    public static string ProfileImage(this IIdentity identity) 
    { 
     var claim = ((ClaimsIdentity)identity).FindFirst("ProfileImage"); 
     // Test for null to avoid issues during local testing 
     return (claim != null) ? claim.Value : string.Empty; 
    } 
} 

Который дает мне результат использования User.Identity.ProfileImg(); и т.д ..

+0

я надеюсь, что это получает в ответ, потому что я хотел бы знать сам. – conterio

+0

Я получаю ответ о том, как я решил его, когда вернусь к своему компьютеру. @JeremyConterio – Rovdjuret

+0

, что было бы замечательно – conterio

ответ

4

Извините за то, что вы, ребята, подождите!

Я решил это, выполнив следующие действия при создании пользователя. Как и в моем случае, когда пользователь создан, я создаю претензии, которые хранятся как отношение к пользователю. Затем я сохраняю эти значения обновленными в течение всего процесса, что означает, что каждый раз, когда кто-то меняет значения, они должны быть обновлены в таблице претензий.

var user1 = new ApplicationUser() 
{ 
    Firstname = "MyName", 
    Lastname = "MyLastname", 
    UserName = "[email protected]", 
    Email = "[email protected]", 
    EmailConfirmed = true, 
    PhoneNumber = "000000000", 
    OrganizationId = organization.Id, 
    ProfileImageUrl = "user.jpg" 
}; 
await userManager.CreateAsync(user1, "Qwerty1!"); 
await userManager.AddToRoleAsync(user1, "SuperAdmin"); 

var claims1 = new List<Claim> { 
    new Claim("Email", user1.Email), 
    new Claim("FullName", string.Format("{0} {1}", user1.Firstname, user1.Lastname)), 
    new Claim("Organization", organization.Name), 
    new Claim("Role", "SuperAdmin"), 
    new Claim("ProfileImage", user1.ProfileImageUrl) 
}; 

await userManager.AddClaimsAsync(user1, claims1); 

Последнее, но не менее важное. Я создаю расширение, чтобы получить доступ к ним для текущего пользователя в режимах просмотра и контроллеров.

using System.Security.Claims; 
using System.Security.Principal; 

namespace Core.Extensions 
{ 
    public static class IdentityExtension 
    { 
     public static string FullName(this IIdentity identity) 
     { 
      var claim = ((ClaimsIdentity)identity).FindFirst("FullName"); 
      return (claim != null) ? claim.Value : string.Empty; 
     } 

     public static string Organization(this IIdentity identity) 
     { 
      var claim = ((ClaimsIdentity)identity).FindFirst("Organization"); 
      return (claim != null) ? claim.Value : string.Empty; 
     } 

     public static string Role(this IIdentity identity) 
     { 
      var claim = ((ClaimsIdentity)identity).FindFirst("Role"); 
      return (claim != null) ? claim.Value : string.Empty; 
     } 

     public static string ProfileImage(this IIdentity identity) 
     { 
      var claim = ((ClaimsIdentity)identity).FindFirst("ProfileImage"); 
      return (claim != null) ? claim.Value : string.Empty; 
     } 

     public static string Email(this IIdentity identity) 
     { 
      var claim = ((ClaimsIdentity)identity).FindFirst("Email"); 
      return (claim != null) ? claim.Value : string.Empty; 
     } 
    } 

} 

Тогда я могу использовать, как это, на мой взгляд, например

@using Microsoft.AspNetCore.Identity 
@using Core.Extensions 
@{ 
    ViewData["Title"] = "Overview"; 
} 
<h4 class="mt-0 mb-5">Welcome back @User.Identity.FullName()</h4> 
Смежные вопросы