skip to Main Content

I have this endpoint method:

var authToken = await [url]
                    .AddAuthHeaders(config)
                    .PostJsonAsync(new AuthTokenRequest
                    {
                        GrantType = "test",
                        ClientId = "test",
                        ClientSecret = "test",
                        Audience = "test"
                    })
                    .ReceiveJson<AuthTokenResponse>();

It’s calling this endpoint:

[HttpPost]
public IActionResult Get([FromBody] object request)
{
    try
    {
        var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.Name, "test")
                }),
                Issuer = _issuer,
                Audience = _audience,
                SigningCredentials = new SigningCredentials(
                    new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_key)),
                    SecurityAlgorithms.HmacSha512Signature)
            };

        var tokenHandler = new JwtSecurityTokenHandler();
        var token = tokenHandler.CreateToken(tokenDescriptor);

        // Create a new instance of the AuthTokenResponse class and set its properties
        var response = new AuthTokenResponse
            {
                AccessToken = tokenHandler.WriteToken(token).ToString(),
                TokenType = "Bearer",
                ExpiresSeconds = token.ValidTo.Subtract(token.ValidFrom).TotalSeconds.ToString(),
                AuthTokenType = AuthTokenType.Generic
            };

        return Ok(response);
    }
    catch (Exception ex)
    {
        _logger.LogError(ex, "Error generating token for request {Request}", request);
        return BadRequest();
    }
}

My AuthTokenReponse class is:

[DataContract]
public class AuthTokenResponse
{
    [DataMember(Name = "access_token")]
    public string AccessToken { get; set; }

    [DataMember(Name = "token_type")]
    public string TokenType { get; set; }

    [DataMember(Name = "expires_in")]
    public string ExpiresSeconds { get; set; }

    public AuthTokenType AuthTokenType { get; set; }
}

public enum AuthTokenType
{
    Generic,
    Custom
}

Now when I call the endpoint using the post method, it hits the end point as it should, and I can see the response object generate all the correct properties. It generates a token, which I can clearly see and returns a valid response object.

However, the application receiving the object, receives this:

                AccessToken null
                TokenType null
                ExpiresSeconds null
                AuthTokenType Generic

Everything is null, apart from AuthTokenType, which has the correct value.

when i use postman i get the correct values

{
    "accessToken": "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6Indob2NhcmVzaXRzZmFrZSIsIm5iZiI6MTY4MzMxNDAxMiwiZXhwIjoxNjgzMzE3NjEyLCJpYXQiOjE2ODMzMTQwMTIsImlzcyI6Imh0dHBzOi8vbG9jYWxob3N0OjUwODg5LyIsImF1ZCI6Imh0dHBzOi8vbG9jYWxob3N0OjUwODg5LyJ9.W_qvEBeF4gGMYAKA6n09bYPWsKrWvpEwRc0b7DdZuNJf4RDU25yh3GUv5Ht0UupoBqGYHDBfBjR8O21sv-56rg",
    "tokenType": "Bearer",
    "expiresSeconds": "3600",
    "authTokenType": 0
} 

I can’t work out why this is? Is it that that the object is not serializing its properties? Any thoughts?

2

Answers


  1. Chosen as BEST ANSWER

    the problem seemed to be that

    ReceiveJson expects a json serialised object,

    I fixed this by serialising the object before sending

                var json = JsonConvert.SerializeObject(response);
    
                return Ok(json);
    

  2. The problem seems to be the data contract attributes. Assuming you are using the default Flurl serializer – Newtonsoft’s Json.NET which will honor the attributes (see the docs). Either remove DataMember attributes or add JsonProperty ones (which will take precedence):

    [DataContract]
    public class AuthTokenResponse
    {
        [DataMember(Name = "access_token")]
        [JsonProperty("accessToken")]
        public string AccessToken { get; set; }
    
        [DataMember(Name = "token_type")]
        [JsonProperty("tokenType")]
        public string TokenType { get; set; }
    
        [DataMember(Name = "expires_in")]
        [JsonProperty("expiresSeconds")]
        public string ExpiresSeconds { get; set; }
    
        public AuthTokenType AuthTokenType { get; set; }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search