locked
Get Current User With Token Base RRS feed

  • Question

  • User338455301 posted

    Hi, 

    i want get user by the token that in login its set for him.

    LoginApi

    [HttpPost("login")]
            public async Task<IActionResult> Login([FromBody]   LoginViewModel login)
    
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest("The Model State Is Not Valid");
                }
               
                var user = await _userRepository.GetAsync(x => x.UserName == login.Username);
    
                if (user == null)
                    return BadRequest(new { username = "نام کاربری یا رمز عبور اشتباه می باشد" });
    
    
                return Ok(new { token = CreateToken(user) });
            }
     public string CreateToken(ApplicationUser user)
            {
                var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Verify"));
                var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
                var tokenOption = new JwtSecurityToken(
                    issuer: "http://localhost:55705",
                    claims: new List<Claim>
                    {
                        new Claim(ClaimTypes.Name,user.UserName),
                        new Claim(ClaimTypes.Role,"Customer")
                    }
                    );
                return new JwtSecurityTokenHandler().WriteToken(tokenOption);
            }

    It's True?
    but how get current user with his token ?

    Tuesday, July 9, 2019 8:11 AM

Answers

All replies

  • User475983607 posted

    You shared code that creates the token but nothing else.  

    Tuesday, July 9, 2019 11:45 AM
  • User-474980206 posted

    you need to decided how the token is passed to requests. you can make it part of the request, or more common use it as bearer token. once you decide how to pass the token, on the server you extract the token and call  SecurityToken.ReadToken(token). then you just get the username claim from the result.

    Tuesday, July 9, 2019 3:40 PM
  • User1724605321 posted

    Hi elahimahdi ,

    In your client app ,  You can decode the access token to get the claims  :

    How to decode JWT Token? .

    Decoding and verifying JWT token using System.IdentityModel.Tokens.Jwt

    And then use cookie authentication for sign in :

     var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role);
     identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, loginData.Username));
     identity.AddClaim(new Claim(ClaimTypes.Name, loginData.Username));
     //add your custom claims 
     ....
    
     var principal = new ClaimsPrincipal(identity);
     await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = loginData.RememberMe });

    Best Regards,

    Nan Yu

    Wednesday, July 10, 2019 2:11 AM
  • User338455301 posted

    thanks but,

    i want get user in server , no in client app 

    how to get user from token that its sent from client app ?

    Wednesday, July 10, 2019 1:01 PM
  • User475983607 posted

    elahi1mahdi

    thanks but,

    i want get user in server , no in client app 

    how to get user from token that its sent from client app ?

    It is a bit unclear why you do not know how your application is supposed to work.  Usually, a JWT token is send in the HTTP Authorization header.

    Authorization : Bearer adslkfjalkdsjf8y4lksndf94.dfadsfa.sdfsfdg

    Your Web API application must be configured to read the token then allow access to an Action using the [authorize] attribute.  The .NET framework has everything you need to accomplish this task.

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/individual-accounts-in-web-api

    Wednesday, July 10, 2019 1:33 PM
  • User1724605321 posted

    Hi elahi1mahdi ,

    You can use AddJwtBearer middleware(assume your are using .net core web api) to validate/decode token and fill the claims principle :

      services.AddAuthentication(x =>
                {
                    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddJwtBearer(x =>
                {
                    x.RequireHttpsMetadata = false;
                    x.SaveToken = true;
                    x.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(key),
                        ValidateIssuer = false,
                        ValidateAudience = false
                    };
                });

    https://jasonwatmore.com/post/2018/08/14/aspnet-core-21-jwt-authentication-tutorial-with-example-api

    https://wildermuth.com/2018/04/10/Using-JwtBearer-Authentication-in-an-API-only-ASP-NET-Core-Project

    Best Regards,

    Nan Yu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, July 11, 2019 1:51 AM