如何做好会议管理ASPNET身份? [英] How to do session management in aspnet identity?

查看:134
本文介绍了如何做好会议管理ASPNET身份?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的 Asp.net身份对于登录,注册,忘记密码的等和源$ C ​​$ C从该采取以下链接:

I am using Asp.net identity for Login,Register,Forgot Password etc and source code is taken from this below link:

<一个href=\"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

<一个href=\"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.

现在我有1台是UserMaster和登记过程中我问这个以下字段:
全名,EMAILID,密码,ContactNumber,性别

Now i have 1 table that is UserMaster and during registration i am asking for this following fields: FullName,EmailId,Password,ContactNumber,Gender.

我UserMaster包含此以下字段:标识,全名,EMAILID,ContactNumber,性别

My UserMaster Contains this following fields:Id,FullName,EmailId,ContactNumber,Gender

现在,当用户提交注册成为本全名,EMAILID,ContactNumber,性别将被保存在 UserMaster 随着电子邮件,密码将被保存在AspnetUser

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.

2以上的链接,提供了我的注册方法是一样的。

在这里,你可能会注意到,有我UserMaster和AspnetUser之间没有关系所以在登录时,当用户输入自己的电子邮件ID登录我会用这种方法等待SignInManager。 PasswordSignInAsync 来验证用户,如果这个方法返回成功,那么我会做什么是使用这个电子邮件ID,然后在我的UserMaster检查此电子邮件,并在那里比赛将发现我将从UserMaster获取该用户ID和存储它在会议上,并使用thorugh了我的申请,我登录方法如下图所示:

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:

 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;
                            }

这是一种适当的方式或仍然是一个更好的办法,我想整个存储用户对象,而不是只是存储的用户ID。

Is this an appropriate way or still a better way and i want to store entire user object instead of just storing User Id.

所以有谁能够告诉我如何与ASPNET身份做到这一点?

So can anybody tell me how to do this with aspnet identity??

推荐答案

。这是很容易与定制要求延长。

Since you are using Asp.Net Identity, you want to store session related stuff as claims. This is very easy to extend with customised claims.

顺便说一句,我想你会更好简单的延长 ApplicationUser 来容纳额外的数据,详见<一个href=\"http://www.asp.net/mvc/overview/security/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on#ap\">here.

As an aside, I think you'd be better off simple extending ApplicationUser to hold the additional data, as detailed here.

这是说,这里是如何自定义声明类型添加到您的应用程序一个完整的例子。

That said, here is a complete example of how to add custom claim types to your application.

第1步 - 定义一个或多个自定义声明类型来保存你的其他信息

Step 1 - Define one or more custom claim types to hold your additional information

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.

第2步 - 在过程中的符号,为自定义声明类型设定值

Step 2 - During the sign in process, set values for the custom claim types

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);
}

请注意:我们使用的自定义声明类型,以便我们preserve现有的的NameIdentifier 名称索赔,所以可以很容易地从两个Asp.Net身份并获取身份信息我们自定义的 UserMaster 表。

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.

第3步 - 扩展方法(S)添加到的IIdentity ,所以我们可以轻松地访问我们的自定义声明数据

Step 3 - Add extension method(s) to IIdentity so we can easily access our custom claim data

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;
    }
}

没什么特别的在这里。我们只投了的IIdentity ClaimsIdentity ,然后返回或者给定的<$ c第一次债权价值$ C> CustomClaimType 我们发现,或者我们返回如果索赔不存在。

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.

第四步 - 现在我们可以真正轻松地访问我们的观点和/或控制器自定义声明的数据。假设你想从你的 UserMaster 表而不是 ApplicationUser 使用的全名?现在,你可以这样做:

Step 4 - Now we can access our custom claim data in views and/or controllers really easily. Say you wanted to use the full name from your UserMaster table instead of the 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.

这篇关于如何做好会议管理ASPNET身份?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆