本文介绍了如何使用 ASP.NET Identity 2.0 来允许用户模拟另一个用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将 ASP.NET MVC 5.1 应用程序从 MembershipProvider 迁移到 ASP.NET Identity v2.0.我在该应用程序中的一项功能是用户模拟:管理员可以作为在网站上注册的任何其他用户登录,而无需知道密码.

I'm migrating a ASP.NET MVC 5.1 application from MembershipProvider to ASP.NET Identity v2.0. One of the features I have in the application is user impersonation: Administrators can be logged in as any other user registered on the site without knowing passwords.

我使用此代码为 MembershipProvider 实现用户模拟这不适用于身份库.

I used this code to implement user impersonation for the MembershipProvider and this does not work with Identity library.

如何在 ASP.NET Identity 中实现用户模拟(而不是 IIS 模拟)?

How do I implement user impersonation (not IIS impersonation) in ASP.NET Identity?

推荐答案

我已经找到了解决这个问题的方法.

I've found a solution to this problem.

基本上我使用管理员用户名添加声明,如果此声明存在,我知道正在发生冒充.当管理员想要停止模拟时,系统会检索声明的原始用户名,删除旧的模拟 cookie 并为管理员创建一个新的 cookie:

Basically I add claim with admin username, if this claim exists, I know that impersonation is happening. When admin wants to stop impersonation, system retrieves original username for the claims, deletes old impersonated-cookie and creates a new cookie for the admin:

[AuthenticateAdmin] // <- make sure this endpoint is only available to admins
public async Task ImpersonateUserAsync(string userName)
{
    var context = HttpContext.Current;

    var originalUsername = context.User.Identity.Name;

    var impersonatedUser = await userManager.FindByNameAsync(userName);

    var impersonatedIdentity = await userManager.CreateIdentityAsync(impersonatedUser, DefaultAuthenticationTypes.ApplicationCookie);
    impersonatedIdentity.AddClaim(new Claim("UserImpersonation", "true"));
    impersonatedIdentity.AddClaim(new Claim("OriginalUsername", originalUsername));

    var authenticationManager = context.GetOwinContext().Authentication;
    authenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
    authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, impersonatedIdentity);
}

更多信息在我的博客文章中:使用 ASP.Net Identity 2 进行用户模拟.

More information is in my blog-post: User impersonation with ASP.Net Identity 2.

2017 年 7 月更新:这个话题非常流行,所以我研究了 Core 中的用户模拟,并且原则与更新的 API 非常相似.以下是模拟方法:

Upd July 2017: this topic is quite popular, so I've looked into user impersonation in Core and principles are very similar with updated API. Here is how to impersonate:

    [Authorize(Roles = "Admin")] // <-- Make sure only admins can access this 
    public async Task<IActionResult> ImpersonateUser(String userId)
    {
        var currentUserId = User.GetUserId();

        var impersonatedUser = await _userManager.FindByIdAsync(userId);

        var userPrincipal = await _signInManager.CreateUserPrincipalAsync(impersonatedUser);

        userPrincipal.Identities.First().AddClaim(new Claim("OriginalUserId", currentUserId));
        userPrincipal.Identities.First().AddClaim(new Claim("IsImpersonating", "true"));

        // sign out the current user
        await _signInManager.SignOutAsync();

        // If you use asp.net core 1.0
        await HttpContext.Authentication.SignInAsync(cookieOptions.ApplicationCookieAuthenticationScheme, userPrincipal);
        // If you use asp.net core 2.0 (the line above is deprecated)
        await HttpContext.SignInAsync(cookieOptions.ApplicationCookieAuthenticationScheme, userPrincipal);

        return RedirectToAction("Index", "Home");
    }

这是如何阻止冒充:

    [Authorize(Roles = "Admin")] // <-- Make sure only admins can access this 
    public async Task<IActionResult> StopImpersonation()
    {
        if (!User.IsImpersonating())
        {
            throw new Exception("You are not impersonating now. Can't stop impersonation");
        }

        var originalUserId = User.FindFirst("OriginalUserId").Value;

        var originalUser = await _userManager.FindByIdAsync(originalUserId);

        await _signInManager.SignOutAsync();

        await _signInManager.SignInAsync(originalUser, isPersistent: true);

        return RedirectToAction("Index", "Home");
    }

完整解释在我的博客:http://tech.trailmax.info/2017/07/user-impersonation-in-asp-net-core/GitHub 上的完整代码示例:https://github.com/trailmax/AspNetCoreImpersonation

Full explanation in my blog: http://tech.trailmax.info/2017/07/user-impersonation-in-asp-net-core/ Full code sample on GitHub: https://github.com/trailmax/AspNetCoreImpersonation

这篇关于如何使用 ASP.NET Identity 2.0 来允许用户模拟另一个用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 08:31