C# - ASP.NET Core 2.0 - Json Web Token

0

Mam problem z uwierzytelnieniem. Tworzę jwt token po zalogowaniu, lecz gdy chcę go przesłać aby wejść do endpointa wymagającego uwierzytelnienia, to dostaje 401.

[AllowAnonymous]
[Route("users/login")]

public async Task<JWT> login([FromBody]Login command)
{
    var user = GETUSER

    if (user == null)
    {
       ERROR
    }
    if (user.Password != command.password)
    {
       ERROR
    }

    return BuildToken(user); 
}
[Authorize]
[Route("users/test")]
public string test()
{
    return "test";
}
private JWToken BuildToken(User user)
{
    var now = DateTime.UtcNow;

    var claims = new Claim[]
    {
        new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
        new Claim(JwtRegisteredClaimNames.UniqueName, user.Id.ToString()),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
        new Claim(JwtRegisteredClaimNames.Iat, now.JWT_ToTimestamp().ToString()),
    };

    var expires = now.AddHours(1);

    var signingCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"])),
        SecurityAlgorithms.HmacSha256);
    var jwt = new JwtSecurityToken(
        issuer: _config["Jwt:Issuer"],
        claims: claims,
        notBefore: now,
        expires: expires,
        signingCredentials: signingCredentials
    );

    var token = new JwtSecurityTokenHandler().WriteToken(jwt);

    return new JWToken 
    {
        Token = token,
        Expires = expires.ToTimestamp()
    };
}

W zwrotce dostaje

{
    "token": "eyJhbGciO(...)",
    "expires": 1531785151253
}

Której później używam w POSTMAN/Authorization (załącznik)
postman.png

W configure services mam

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = Configuration["Jwt:Issuer"],
        ValidAudience = Configuration["Jwt:Issuer"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])),
        ClockSkew = TimeSpan.Zero
    };
});

GUID w Claims zgadza się z GUIDem obiektu.

Pomysły?

0

Pokaż jak wygląda token po odkodowaniu: https://jwt.io/

0
{
  "alg": "HS256",
  "typ": "JWT"
}
{
  "sub": "e9221e00-d533-43ff-4822-08d5ebadec76",
  "unique_name": "e9221e00-d533-43ff-4822-08d5ebadec76",
  "jti": "bb28dfb3-6458-487a-becb-1a9cae2df510",
  "nbf": 1531808660,
  "exp": 1531812260,
  "iss": "http://localhost:55658/"
}
0

Proponuję pokazać jeszcze przykładowe wywołanie API (chodzi mi o wysłane nagłówki). Może Postman nie wysyła ich? W przeciwnym wypadku w odpowiedzi serwera radzę sprawdzić nagłówki, tam pojawi się komunikat o błędzie.

1

!!!!!!!!! <3

Tutaj był błąd:

options.TokenValidationParameters = new TokenValidationParameters
{
	(...)
	ValidateAudience = true,
}

Bo nie ustawiałem nigdzie Audience, a Validate było na true

Wystarczy zrobić false i działa, dzięki.

1 użytkowników online, w tym zalogowanych: 0, gości: 1