Pretend to be a user in the standard ASP.NET MVC installation template

I installed a standard ASP.NET MVC site with basic authentication. I added roles, so new users get a specific role.

Now I want you to be able to personalize the user.

Outstanding Advice

The personification when searching around is as follows:

     FormsAuthentication.SetAuthCookie(user.UserName, false);

This does not work by default, since you need to do two things:

1

Enable Authentication:

 <system.web>
    <authentication mode="Forms" />
  </system.web>

2:

Unplug the module:

<system.webServer>
    <modules>
      <!--<remove name="FormsAuthentication" />-->
    </modules>
    <staticContent>

Task

However, doing this leaves a few problems.

  • When you personify yourself, you cannot log out. This is easily fixed by adding the following to LogOut:FormsAuthentication.SignOut();
  • User.IsInRole(Constants.Roles.Creditor); stops working, so we can’t check if the user is in the role

What to do?

- , - , . , ?

"Forms", , , "". , :

  • A) -, web.config
  • B)

?: -)

+4
2

, , Id , , , (Cookie, Cache, Db ..).

- . , .

, :

, -

        var claims = await UserManager.GetClaimsAsync(CurrentUserId);
        var claim = claims.FirstOrDefault(c => c.Type == "Impersonate");
        if (claim!=null)
        {
            //You may forget to remove it or the user could end there session before you are able to
            var r = await UserManager.RemoveClaimAsync(CurrentUserId, claim);
        }
        var result = await UserManager.AddClaimAsync(CurrentUserId, new Claim("Impersonate", userId));

        if (!result.Succeeded)
        {
            return GetErrorResult(result);
        }

, . , . , .

https://docs.microsoft.com/en-us/aspnet/core/security/authorization/claims

.

, , , - . , , .

+4

IsInRole() main, .

User , Identities. Default , .

,

public class CustomPricipal : IPrincipal
{        
    public CustomPricipal(string username)
    {
        this.Identity = new CustomIdentity(username);
    }

    public IIdentity Identity
    {
        get;
        private set;
    }

    public bool IsInRole(string role)
    {
        return this.Identity != null && ((CustomIdentity)this.Identity).Roles.Any(x => x.ToLower() == role.ToLower());
    }
}

public class CustomIdentity : IIdentity
{
    public CustomIdentity(string name)
    {
        // We can fetch the user information from database and create custom properties
        this.Name = name;
        this.IsAuthenticated = true;
        this.AuthenticationType = "Forms";
        this.Roles = new List<string>() { "Admin", "SuperAdmin" };
    }
    public string AuthenticationType
    {
        get;
        private set;
    }

    public bool IsAuthenticated
    {
        get;
        private set;
    }

    public string Name
    {
        get;
        private set;
    }
    public List<string> Roles
    {
        get;
        private set;
    }
}

global.asax.cs

    public override void Init()
    {
        this.PostAuthenticateRequest += MvcApplication_PostAuthenticateRequest;
        base.Init();
    }

    void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
    {
        if (Request.IsAuthenticated)
        {
            HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
            if (authCookie != null)
            {
                FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);                    
                Context.User = Thread.CurrentPrincipal = new CustomPricipal(authTicket.Name);
            }
        }
    }

User.IsInRole("")

+1

Source: https://habr.com/ru/post/1690794/


All Articles