Context.User.Identity.IsAuthenticated is always false in jwt token?

mc 5,426 Reputation points
2021-11-15T01:28:35.68+00:00

I am using signalr with jwt token.
`services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
var id = context.Request.Query["id"];
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrWhiteSpace(accessToken) && path.StartsWithSegments("/ddjhub"))
{
context.Token = accessToken;
}

                      return Task.CompletedTask;
                  }
            };
        });`

the accessToken is valid but Context.User.Identity.IsAuthenticated is always false.

why?

I just write the token to the client. need I use other like SignInAsync?

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

Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2021-11-16T08:52:51.52+00:00

    Hi @mc ,

    When using JWT token authentication and validate the token, the server will get the token from the request header with the 'Authentication' key, after that validate it. If the token is valid, the user can continue accessing the resource, otherwise it will show the not permission notification message. You can refer to the following screenshot:

    149761-5.gif

    From your code, it seems that the access_token (it is the JWT token, right?) is in the query string, right? Try to use F12 developer Network tool or Fiddler to check it. And then try to add the JWT token at the request header with the 'Authentication' key.

    You can also refer to Brando's reply in this thread: add the custom middleware to add the JWT token at the request header:

        app.Use(async (context, next) =>  
        {  
            var JWToken = context.Session.GetString("JWToken");  
            if (!string.IsNullOrEmpty(JWToken))  
            {  
                context.Request.Headers.Add("Authorization", "Bearer " + JWToken);  
            }  
            await next();  
        });  
        app.UseAuthentication();  
        app.UseAuthorization();  
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.