User1010234884 posted
Hello,
I have a little problem with claims with asp web api authentication, I have the default authentication with asp web api with this code:
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
string pass = Encrypt_MD5(context.Password);
var user = await _ctx.tbl_users.Where(a => a.email == context.UserName && a.password == pass).Select(x => new UserModel
{
username = x.username,
email = x.email
}).FirstOrDefaultAsync();
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, user.username), }, OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesIdentity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, user.username), }, CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user.username);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
and it works well, but I need to add a claim after the success login, because I need to capture some CompanyID from a api controller, and I have this:
[Route("api/auth/{id_company}/companysession")]
[HttpPost]
public HttpResponseMessage FilterCountry(int id_company)
{
var context = HttpContext.Current;
var originalUsername = context.User.Identity.Name;
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, originalUsername));
claims.Add(new Claim("CompanyID", id_company.ToString()));
var impersonatedIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationType);
Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType);
Authentication.SignIn(impersonatedIdentity);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, "Session Succefully: " + id_company);
return response;
}
but it not works, I tried and read a lot of posts, documentation, etc, but I can not make it work, please I need help with this, my intention is that once I have the CompanyID claim, I can use the claim on any controller like this
[Route("api/gatewayslines")]
[HttpGet]
public IEnumerable<GatewayModelTreeView> gatewayslines()
{
var id_company = ((ClaimsIdentity)User.Identity).Claims.FirstOrDefault(x => x.Type == "CompanyID").Value;
var result = this._gatewayServices.getGatewaysTree(User.Identity.Name.ToString(), Convert.ToInt32(id_company));
return result;
}
I appreciate any help, thanks and best regards