Answer the question
In order to leave comments, you need to log in
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);
}
}
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
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question