locked
Add claims on successful login and retrieve it elsewhere in the application RRS feed

  • Question

  • 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

    Thursday, March 17, 2016 5:28 PM

Answers

  • User-986267747 posted

    Hi lvasquez20,

    lvasquez20

    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

    lvasquez20

    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:

    According to your code, it seems fine. You could debug your code and check what is the list of the claims. In my experience, if you'd like to add a claim after the user login in the website successfully and you could access to claims wherever we want. I suggest that you could store claims in a database.  

    Since the list of claims is a queryable, you can pretty much do whatever LINQ query you want on it, Where, Count, etc.

    To add a new claim:

    await UserManager.AddClaimAsync(userId, new Claim("SomeClaimType", claimValue));

    Then we could get the current user's id and get all claims for the user, finally, once you have the claims, to pull out a specific one:

    var userId = User.Identity.GetUserId();
    
    var claims = await UserManager.GetClaimsAsync(userId);
    
    var someClaim = claims.FirstOrDefault(c => c.Type == "SomeClaimType");

    Besides, you could refer to the following links to get more information about adding claims.

    http://stackoverflow.com/questions/21762077/asp-net-identity-and-claims

    I hope it's helpful to you.

    Best Regards,

    Klein zhang

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, March 18, 2016 3:19 AM