简体   繁体   English

如何在aspnet身份中进行会话管理?

[英]How to do session management in aspnet identity?

I am using Asp.net identity for Login,Register,Forgot Password etc and source code is taken from this below link:我使用Asp.net 身份进行登录、注册、忘记密码等,源代码取自以下链接:

http://www.asp.net/mvc/overview/security/create-an-aspnet-mvc-5-web-app-with-email-confirmation-and-password-reset http://www.asp.net/mvc/overview/security/create-an-aspnet-mvc-5-web-app-with-email-confirmation-and-password-reset

http://www.asp.net/identity/overview/features-api/account-confirmation-and-password-recovery-with-aspnet-identity . http://www.asp.net/identity/overview/features-api/account-confirmation-and-password-recovery-with-aspnet-identity

Now i have 1 table that is UserMaster and during registration i am asking for this following fields: FullName,EmailId,Password,ContactNumber,Gender .现在我有 1 个表是 UserMaster 并且在注册期间我要求以下字段: FullName,EmailId,Password,ContactNumber,Gender

My UserMaster Contains this following fields: Id,FullName,EmailId,ContactNumber,Gender我的 UserMaster 包含以下字段: Id、FullName、EmailId、ContactNumber、Gender

Now when user will submit registration form this FullName,EmailId,ContactNumber,Gender will be saved in UserMaster along with the Email,Password will be saved in AspnetUser .现在,当用户提交注册表时,此 FullName,EmailId,ContactNumber,Gender 将与电子邮件一起保存在UserMaster 中,密码将保存在 AspnetUser 中

My Register Method is same as provided in above 2 links.我的注册方法与上述 2 个链接中提供的相同。

Here you might notice that there is no relationship between my UserMaster and AspnetUser so during login when user will enter his email id to login i will use this method await SignInManager.PasswordSignInAsync to verify user and if this method returns success then what i will do is use this email id and check this email in my UserMaster and where match will be found i will fetch that UserId from UserMaster and store it in session and use thorugh out my application in my login method like below:在这里您可能会注意到我的 UserMaster 和 AspnetUser 之间没有关系,因此在登录期间,当用户输入他的电子邮件 ID 进行登录时,我将使用此方法await SignInManager.PasswordSignInAsync来验证用户,如果此方法返回成功,那么我将做的是使用此电子邮件 ID 并在我的 UserMaster 中检查此电子邮件,并在何处找到匹配项,我将从 UserMaster 获取该 UserId 并将其存储在会话中,并在我的登录方法中使用我的应用程序,如下所示:

 public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
            {
                if (!ModelState.IsValid)
                {
                    return View(model);
                }

                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, change to shouldLockout: true
                var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
                switch (result)
                {
                    case SignInStatus.Success:
                  using (var context = new MyEntities())
                        {
                            var fetchUSerId = context.UserMaster.Where(t => t.Email == model.Email).Select(t=>t.UserId).SingleOrDefault();
                            Session["UserId"] = fetchUSerId;
                        }
                        return RedirectToLocal(returnUrl);
                    case SignInStatus.LockedOut:
                        return View("Lockout");
                    case SignInStatus.RequiresVerification:
                        return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
                    case SignInStatus.Failure:
                    default:
                        ModelState.AddModelError("", "Invalid login attempt.");
                        return View(model);
                }
            }

I am talking about this in my login method:我在我的登录方法中谈论这个:

 case SignInStatus.Success:
                      using (var context = new MyEntities())
                            {
                                var fetchUSerId = context.UserMaster.Where(t => t.Email == model.Email).Select(t=>t.UserId).SingleOrDefault();
                                Session["UserId"] = fetchUSerId;
                            }

Is this an appropriate way or still a better way and i want to store entire user object instead of just storing User Id.这是一种合适的方式还是更好的方式,我想存储整个用户对象而不是只存储用户 ID。

So can anybody tell me how to do this with aspnet identity??那么有人可以告诉我如何使用aspnet身份做到这一点吗?

Since you are using Asp.Net Identity, you want to store session related stuff as claims.由于您使用的是 Asp.Net Identity,因此您希望将与会话相关的内容存储为声明。 This is very easy to extend with customised claims.这很容易通过自定义声明进行扩展。

As an aside, I think you'd be better off simple extending ApplicationUser to hold the additional data, as detailed here .顺便说一句,我认为您最好简单地扩展ApplicationUser来保存额外的数据,详情见此处

That said, here is a complete example of how to add custom claim types to your application.也就是说,这里有一个完整的示例,说明如何向您的应用程序添加自定义声明类型。

Step 1 - Define one or more custom claim types to hold your additional information第 1 步- 定义一个或多个自定义声明类型以保存您的附加信息

public static class CustomClaimTypes
{
    public const string MasterFullName = "http://schemas.xmlsoap.org/ws/2014/03/mystuff/claims/masterfullname";
    public const string MasterUserId = "http://schemas.xmlsoap.org/ws/2014/03/mystuff/claims/masteruserid";
}

A claim type is just a unique string that identifies the specific claim.声明类型只是标识特定声明的唯一字符串。 Here we are just using a similar format as the built in claim types.在这里,我们只是使用与内置声明类型类似的格式。

Step 2 - During the sign in process, set values for the custom claim types第 2 步- 在登录过程中,为自定义声明类型设置值

private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
    var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

    //Fetch data from the UserMaster table 
    var userdata = GetdatafromUserMaster();

    //Using the UserMaster data, set our custom claim types
    identity.AddClaim(new Claim(CustomClaimTypes.MasterUserId, userdata.UserId));
    identity.AddClaim(new Claim(CustomClaimTypes.MasterFullName, userdata.FullName));

    AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}

Note: we are using custom claim types so that we preserve the existing NameIdentifier and Name claims, and can therefore easily access identity information from both Asp.Net Identity and our custom UserMaster table.注意:我们使用自定义声明类型,以便保留现有的NameIdentifierName声明,因此可以轻松访问来自 Asp.Net Identity自定义UserMaster表的身份信息。

Step 3 - Add extension method(s) to IIdentity so we can easily access our custom claim data第 3 步- 向IIdentity添加扩展方法,以便我们可以轻松访问我们的自定义声明数据

public static class IdentityExtensions
{
    public static string GetMasterUserId(this IIdentity identity)
    {
        if (identity == null)
            return null;

        return (identity as ClaimsIdentity).FirstOrNull(CustomClaimTypes.MasterUserId);
    }

    public static string GetMasterFullName(this IIdentity identity)
    {
        if (identity == null)
            return null;

        return (identity as ClaimsIdentity).FirstOrNull(CustomClaimTypes.MasterFullName);
    }

    internal static string FirstOrNull(this ClaimsIdentity identity, string claimType)
    {
        var val = identity.FindFirst(claimType);

        return val == null ? null : val.Value;
    }
}

Nothing fancy here.这里没什么好看的。 We just cast the IIdentity as a ClaimsIdentity and then return the value of either the first claim of the given CustomClaimType that we find, or we return null if a claim doesn't exist.我们只投中IIdentity作为ClaimsIdentity ,然后返回任何给定的第一个要求的值CustomClaimType我们发现,或者我们返回null ,如果要求不存在。

Step 4 - Now we can access our custom claim data in views and/or controllers really easily.第 4 步- 现在我们可以非常轻松地在视图和/或控制器中访问我们的自定义声明数据。 Say you wanted to use the full name from your UserMaster table instead of the ApplicationUser ?假设您想使用UserMaster表中的全名而不是ApplicationUser You can now do this:你现在可以这样做:

<ul class="nav navbar-nav navbar-right">
    <li>
        @Html.ActionLink("Hello " + User.Identity.GetMasterFullName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
    </li>
    <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
</ul>

You can also do the same thing from within a Controller.您也可以在 Controller 中执行相同的操作。

You can add as:您可以添加为:

var listClaims=new[] { new Claims(ClaimsType.SerialNumber,Id), new Claims(ClaimsType.Name,FullName), new Claims(ClaimsType.HomePhone,ContactNumber), new Claims(ClaimsType.Gender,Gender)};

var oAuthIdentity=new ClaimsIdentity(listClaims, otherparameter ...);

For more details you can check System.Secutity.Claims.ClaimTypes有关更多详细信息,您可以查看 System.Secutity.Claims.ClaimTypes

you may do this:你可以这样做:

var fetchUser = context.UserMaster.Where(t => t.Email == model.Email).SingleOrDefault();
if (null == fetchUser)
    throw new Exception("Not found");
Session["User"] = fetchUser;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 AspNet.Identity角色管理 - AspNet.Identity role Management AspNet Identity RequireClaim() - 如何使用 OR? - AspNet Identity RequireClaim() - How to use OR? ASP MVC 5中的角色管理(Microsoft.AspNet.Identity) - Role Management in ASP MVC 5 (Microsoft.AspNet.Identity) Aspnet Core 身份管理总是让我返回登录页面 - Aspnet Core Identity management always returning me to the login page 如何在 AspNet Core 3 中将 Azure AD 身份验证与基于 SQL 的角色管理结合使用? - How do I use Azure AD authentication with SQL based role management in AspNet Core 3? NHibernate.AspNet.Identity FluentNhibernate-如何将自定义对象添加到ApplicationUSer? - NHibernate.AspNet.Identity FluentNhibernate - how do I add a custom object to my ApplicationUSer? 使用openiddict时如何避免使用Microsoft的Microsoft.AspNet.Identity包 - How do I avoid using Microsofts's Microsoft.AspNet.Identity package when using openiddict 如何使用AspNet.Identity使用Asp.Net MVC5 RTM位登录/验证用户? - How do you login/authenticate a user with Asp.Net MVC5 RTM bits using AspNet.Identity? 以aspnet身份发送电子邮件 - Email sending in aspnet identity 忘记了aspnet身份的密码 - Forgot password in aspnet identity
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM