Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET API Owin login as another user

I'm using Token Based Authentication using ASP.NET Web API 2, Owin, and Identity in my application.

I need functionality to allow a user with "Admin" role to see the information as another (non-admin) user (to log in without a password, with another user's username only).

I don't know how to generate a new token in the controller and save it in session.

like image 782
Yuriy Shkraba Avatar asked Oct 30 '22 16:10

Yuriy Shkraba


1 Answers

I've found a solution to this problem. This is the example of code which returns access token

    /// <summary>
    /// Login as another user (using only a username)
    /// </summary>
    /// <returns>token key</returns>
    [Authorize(Roles = "Admin")]
    [Route("LoginAs")]
    public async Task<IHttpActionResult> GetLoginAs(string userName)
    {
        if (string.IsNullOrEmpty(userName))
            return new System.Web.Http.Results.ResponseMessageResult(
                Request.CreateErrorResponse(
                    (HttpStatusCode)422,
                    new HttpError("UserName null or empty")));
        try
        {
            var userIdentity = UserManager.FindByNameAsync(userName).Result;
            if (userIdentity != null)
            {
                var oAuthIdentity = await userIdentity.GenerateUserIdentityAsync(UserManager,
                Startup.OAuthOptions.AuthenticationType);
                var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());
                var currentUtc = new SystemClock().UtcNow;
                ticket.Properties.IssuedUtc = currentUtc;
                ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(60));
                string accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
                return Ok(accessToken);
            }
            return BadRequest();
        }
        catch (Exception ex)
        {
            return BadRequest();
        }
    }
like image 102
Yuriy Shkraba Avatar answered Nov 11 '22 16:11

Yuriy Shkraba