Two questions about MVC, and Identity

安稳与你 提交于 2019-12-01 12:12:09
Brendan Green

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()

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!