Two questions about MVC, and Identity

后端 未结 2 1391
滥情空心
滥情空心 2021-01-15 21:22

I am very new to identity and MVC, I am trying to create an MVC app as one of my first projects.

I have been able to follow a few tutorials and have successfully add

相关标签:
2条回答
  • 2021-01-15 21:57

    1) I would make your own UserValidator inherit from microsoft's UserValidator and handle your extra field.

    Updated:

    2) You can make your own extension method to get the extra field you added.

    public static string GetSomething(this IIdentity identity)
    {
        if (identity.IsAuthenticated)
        {
            var userStore = new UserStore<ApplicationUser>(new Context());
            var manager = new UserManager<ApplicationUser>(userStore);
            var currentUser = manager.FindById(identity.GetUserId());
            return something = currentUser.something;                
        }
        return null;
    }
    
    0 讨论(0)
  • 2021-01-15 22:17

    Implementing a custom UserValidator has already been covered here: How can customize Asp.net Identity 2 username already taken validation message?

    Rather than hitting the database for every page request to display the handle, add a claim during signin.

    Define your own claim:

    public static class CustomClaimTypes
    {
        public const string Handle = "http://schemas.xmlsoap.org/ws/2014/03/mystuff/claims/handle";
    }
    

    During signin, set the claim:

    private async Task SignInAsync(ApplicationUser user, bool isPersistent, string password = null)
    {
        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
    
        var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
    
        //Get the handle and add the claim to the identity.
        var handle = GetTheHandle();
        identity.AddClaim(new Claim(CustomClaimTypes.Handle, handle);
    
        AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
    }
    

    Then, via an extension method you can read it out the same way as GetUserName():

    public static class IdentityExtensions
    {
        public static string GetHandle(this IIdentity identity)
        {
            if (identity == null)
                return null;
    
            return (identity as ClaimsIdentity).FirstOrNull(CustomClaimTypes.Handle);
        }
    
        internal static string FirstOrNull(this ClaimsIdentity identity, string claimType)
        {
            var val = identity.FindFirst(claimType);
    
            return val == null ? null : val.Value;
        }
    }
    

    Finally, in your view:

    @User.Identity.GetHandle()
    
    0 讨论(0)
提交回复
热议问题