2017-11-21 8 views
1

私はasp.netを初めて使っています。単純な残りのAPIを実行しようとしています。 現在ログインしているユーザーのユーザー名を取得する必要があります。 私はUser.Identity.IsAuthenticatedが真ですが、User.Identity.Nameはnullです。私は認証のためにjwtトークンを使用しています。ここ認証後にASP.netコアAPIでUser.identity.nameがnullになる

は私のログイン方法が

 [HttpPost] 
     public async Task<IActionResult> Login([FromBody] LoginData jsonUser) { 
      IdentityUser claimedUser; 
      try { 
       claimedUser = _userManager.Users.First(
        user => user.Email == jsonUser.username || user.UserName == jsonUser.username); 
      } catch (Exception e) { 
       return NotFound("No user with this username : " + e); 
      } 


      bool isPasswordCorrect = await _userManager.CheckPasswordAsync(claimedUser, jsonUser.Password); 
      return isPasswordCorrect 
       ? Ok(GenerateJwtToken(claimedUser.Email, claimedUser)) 
       : StatusCode(401, "bad login or password"); 
     } 


     //Génération du token JWT 
     private string GenerateJwtToken(string email, IdentityUser user) { 
      var claims = new List<Claim> { 
       new Claim(JwtRegisteredClaimNames.Sub, email), 
       new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), 
       new Claim(ClaimTypes.NameIdentifier, user.Id), 
       new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName), 
       new Claim(JwtRegisteredClaimNames.GivenName, user.UserName) 
      }; 

      var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JwtKey"])); 
      var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); 
      var expires = DateTime.Now.AddDays(Convert.ToDouble(_configuration["JwtExpireDays"])); 

      var token = new JwtSecurityToken(
       _configuration["JwtIssuer"], 
       _configuration["JwtIssuer"], 
       claims, 
       expires: expires, 
       signingCredentials: creds 
      ); 

      return new JwtSecurityTokenHandler().WriteToken(token); 
     } 

どのように私は、現在のユーザー名を取得できますか?

答えて

0

Windows Authenticationenabledで、Anonymous Authenticationは、Visual Studioプロジェクトのプロパティからdisabledであることを確認してください。

コントローラークラスに[Authorize]属性を追加することも検討してください。

関連する問題