question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

JsonReaderException using FromClaim with latest FastEndpoints (4.2 - 4.3.0-beta2)

See original GitHub issue

Expected Behavior

To retrieve user data from the parsed request, which is retrieving claims as request.

Actual Behavior

{
  "status": "Internal Server Error!",
  "code": 500,
  "reason": "'M' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.",
  "note": "See application log for stack trace."
}

Steps to Reproduce the Problem

  1. As package, use FastEndpoints 4.2.0 or highest (at time of writing: 4.3.0-beta2)
  2. Write an Endpoint with requests using FromClaim and a non-FromClaimresponse (same parameters)
  3. Write the endpoint
  4. You get the exception below
public class UserEndpointRequest
{
	[FromClaim(CustomClaimTypes.UserId)]
	public Guid UserId { get; init; }
	[FromClaim(CustomClaimTypes.Name)]
	public string Name { get; init; } = string.Empty;
	[FromClaim(CustomClaimTypes.Email)]
	public string Email { get; init; } = string.Empty;
	//todo fromClaims can not get multi claims of the same type
	[FromClaim(CustomClaimTypes.Roles)]
	public List<string> Roles { get; init; } = new List<string>();
}
public class UserEndpoint : EndpointWithMapping<UserEndpointRequest, UserEndpointResponse, UserEndpointResponse>
{
	public override void Configure()
	{
		Verbs(Http.GET);
		Routes("/user");
		Description(x => x.WithName("user"));
	}

	public override async Task HandleAsync(UserEndpointRequest req, CancellationToken ct) => await SendAsync(MapToEntity(req), cancellation: ct);

	public override UserEndpointResponse MapToEntity(UserEndpointRequest r) =>
		new()
		{
			UserId = r.UserId,
			Name = r.Name,
			Email = r.Email,
			Roles = HttpContext.User.Claims.Where(c => c.Type == CustomClaimTypes.Roles && c.Value.StartsWith("Admin")).Select(c => c.Value)
		};
}
Exception thrown: 'System.Text.Json.JsonException' in System.Private.CoreLib.dll: ''M' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.'
 Inner exceptions found, see $exception in variables window for more details.
 Innermost exception 	 System.Text.Json.JsonReaderException : 'M' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0.
   at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& json, ExceptionResource resource, Byte nextByte, ReadOnlySpan`1 bytes)
   at System.Text.Json.Utf8JsonReader.ConsumeValue(Byte marker)
   at System.Text.Json.Utf8JsonReader.ReadFirstToken(Byte first)
   at System.Text.Json.Utf8JsonReader.ReadSingleSegment()
   at System.Text.Json.Utf8JsonReader.Read()
   at System.Text.Json.Serialization.JsonConverter`1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
at System.Text.Json.ThrowHelper.ReThrowWithPath(ReadStack& state, JsonReaderException ex)
   at System.Text.Json.Serialization.JsonConverter`1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.ReadCoreAsObject(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan`1 utf8Json, JsonTypeInfo jsonTypeInfo, Nullable`1 actualByteCount)
   at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan`1 json, JsonTypeInfo jsonTypeInfo)
   at System.Text.Json.JsonSerializer.Deserialize(String json, Type returnType, JsonSerializerOptions options)
   at FastEndpoints.ReflectionExtensions.<>c__DisplayClass8_0.<GetCompiledValueParser>b__3(Object input)
   at FastEndpoints.Endpoint`2.BindUserClaims(TRequest req, IEnumerable`1 claims, List`1 failures)
   at FastEndpoints.Endpoint`2.BindToModel(HttpContext ctx, List`1 failures, JsonSerializerContext serializerCtx, Boolean dontAutoBindForm, CancellationToken cancellation)
   at FastEndpoints.Endpoint`2.ExecAsync(HttpContext ctx, EndpointDefinition endpoint, CancellationToken cancellation)
   at Microsoft.AspNetCore.Authorization.Policy.AuthorizationMiddlewareResultHandler.HandleAsync(RequestDelegate next, HttpContext context, AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at 

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
EelcoLoscommented, May 23, 2022

Awesome,will check tomorrow morning first thing! Have a fine evening, sir!

1reaction
dj-nitehawkcommented, May 23, 2022

fixed in v4.3.0-beta3

the following now works:

public class Request
{
    public string IdNumber { get; set; }

    [FromClaim("username")]
    public string UserName { get; set; }

    [FromClaim(ClaimTypes.Role)]
    public IEnumerable<string> Roles { get; init; }

}

public class Test : Endpoint<Request>
{
    public override void Configure()
    {
        Get("test");
        Roles("Admin");
        Claims("username");
    }

    public override async Task HandleAsync(Request req, CancellationToken ct)
    {
        await SendAsync(req);
    }
}

public class Login : EndpointWithoutRequest
{
    public override void Configure()
    {
        Get("login");
        AllowAnonymous();
    }

    public override Task HandleAsync(CancellationToken ct)
    {
        Response = JWTBearer.CreateToken(
            signingKey: "xxxxxxxxxxxxxxxx",
            roles: new[] { "Admin", "Manager" },
            claims: ("username", "marko polo"));

        return Task.CompletedTask;
    }
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

FastEndpoints
FastEndpoints is a developer friendly alternative to Minimal APIs & MVC ; 1 Define endpoints in multiple class files (even in deeply nested...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found