Z
Z
zop2016-12-13 19:20:43
ASP.NET
zop, 2016-12-13 19:20:43

Web Api Basic Auth: How to save login and password?

Hello. I continue to make web api. Fastened basic authentication, as described here (through filters).
I use like this:

[IdentityBasicAuthentication]
[Authorize(Roles = "Admin, Client")]
public class MyController : MyApiControllerBase
{
    public async Task<IHttpActionResult> SomeMethod()
    {
        var someManager = new SDK.SomeManager(UserName, Password);
        var result = List<Model>();

        if (User.IsInRole("Client"))
        {
            result = await someManager.ClientMethod();
        }

        if (User.IsInRole("Admin"))
        {
           result = await someManager.AdminMethod();
        }

        return Ok(result);
    }
}

And the basic ApiControllerBase itself:
public class ApiControllerBase : ApiController
{
    protected internal string UserName { get; private set; }
    protected internal string Password { get; private set; }

    public ApiControllerBase()
    {
        SetUserNameAndPassword();
    }

    #region Authorization

    [NonAction]
    private void SetUserNameAndPassword()
    {
        var authHeader = HttpContext.Current.Request.Headers["Authorization"];

        var identity = (ClaimsIdentity)User.Identity;
        IEnumerable<Claim> claims = identity.Claims;

        if (string.IsNullOrEmpty(authHeader) || !authHeader.StartsWith("Basic"))
        {
            Unauthorized();
            return;
        }

        var encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
        var userNameAndPasword = BasicAuthenticationAttribute.ExtractUserNameAndPassword(encodedUsernamePassword);

        if (userNameAndPasword == null)
        {
            Unauthorized();
            return;
        }

        UserName = userNameAndPasword.Item1;
        Password = userNameAndPasword.Item2;

        Ok();
    }

    #endregion
}

Those. I always have login and password from header.
Two things are confusing:
  1. The method from the MyApiControllerBase constructor is called before the authorization filter. I would like to save the login-password in the filter, but where?
  2. How to replace if UserInRole? strategy?

Thank you for your help!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rou1997, 2016-12-13
@Rou1997

No way, they should be saved in the browser, not on the server.

R
Roman, 2016-12-14
@yarosroman

I recommend to fasten token authorization, there is an example in the standard template, you can save roles in the token and save everything.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question