title: How can I authenticate JWT token for each request coming through SignalR hub?
body: <p>I have a React application which is connected to SignalRHub on an ASP.net core app.
  I configured application like that.</p>
  
  <pre><code>public void ConfigureServices(IServiceCollection services)
          {
              services.AddCors(options =&gt;
              {
                  options.AddPolicy("CorsPolicy",
                      builder =&gt; builder.AllowAnyOrigin()
                      .AllowAnyMethod()
                      .AllowAnyHeader()
                      .AllowCredentials());
              });
  
  
             ...
              services.AddAuthentication(x =&gt;
              {
                  x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                  x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
              })
              .AddJwtBearer(x =&gt;
              {
                  x.RequireHttpsMetadata = false;
                  x.SaveToken = true;
                  x.TokenValidationParameters = new TokenValidationParameters
                  {
                      ValidateIssuerSigningKey = true,
                      IssuerSigningKey = new SymmetricSecurityKey(key),
                      ValidateIssuer = false,
                      ValidateAudience = false
                  };
                  x.Events = new JwtBearerEvents
                  {
                      OnMessageReceived = context =&gt;
                      {
  
                          string accessToken = context.Request.Query["access_token"];
  
                          // If the request is for our hub...
                          var path = context.HttpContext.Request.Path;
                          if (!string.IsNullOrEmpty(accessToken) &amp;&amp;
                              (path.StartsWithSegments("/myHub")))
                          {
                              // Read the token out of the query string
                              context.Token = accessToken;
                          }
                          return Task.CompletedTask;
                      }
                  };
              });
  </code></pre>
  
  <p>I'm trying to achieve that </p>
  
  <p>-User logs in with a username and password.</p>
  
  <p>-I create a JWT token.</p>
  
  <pre><code>public User Authenticate(string username, string password)
          {
              var user = _users.SingleOrDefault(x =&gt; x.Username == username &amp;&amp; x.Password == password);
  
              // return null if user not found
              if (user == null)
                  return null;
  
              // authentication successful so generate jwt token
              var tokenHandler = new JwtSecurityTokenHandler();
              var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
              var tokenDescriptor = new SecurityTokenDescriptor
              {
                  Subject = new ClaimsIdentity(new Claim[]
                  {
                      new Claim(ClaimTypes.Name, user.Id.ToString())
                  }),
                  Expires = DateTime.UtcNow.AddMinutes(3),
                  SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
              };
              var token = tokenHandler.CreateToken(tokenDescriptor);
              user.Token = tokenHandler.WriteToken(token);
  
              // remove password before returning
              user.Password = null;
  
              return user;
          }
  </code></pre>
  
  <p>-After that I create a SignalR connection from React side.
   have configured the authentication as shown.</p>
  
  <pre><code>const connection = new signalR.HubConnectionBuilder().withUrl("/myHub", {
      accessTokenFactory: () =&gt; {
          return JSON.parse(localStorage.getItem('user')).token;
      }
  }).configureLogging(0).build();
  </code></pre>
  
  <p>and craeted Hub like that.</p>
  
  <pre><code>[Authorize]
  public class MyHub: Hub
  {    
      [Authorize]
      public async Task SendMessage(string message)
      {
          await Clients.All.SendAsync("MessageReceived", message);
      }
  }
  </code></pre>
  
  <p>The problem is that, when it is trying to open a connection to SignalR hub, it uses JWT token as well. But after that, when it is calling hub methods, it doesn't check whether if JWT still valid or not.</p>
  
  <p>What is the correct way of validating JWT token for each hub method call?</p>