小编Jos*_*ado的帖子

ASP.NET Core 6 JWT 不记名令牌异常

我正在尝试使用 JWT 不记名令牌和谷歌身份验证来实现对 Web API 的身份验证。发现这个答案非常有帮助,但是当它成功验证时,我得到 500,但有以下例外:

System.NullReferenceException:未将对象引用设置为对象的实例。在 Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync() Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware:错误:执行请求时发生未处理的异常。

System.NullReferenceException:未将对象引用设置为对象的实例。在 Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync() 在 Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync() 在 Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.AuthenticateAsync() 在 Microsoft.AspNetCore.Authentication.AuthenticationService .AuthenticateAsync(HttpContext 上下文,字符串方案) 在 Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext 上下文) 在 Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext 上下文)

当令牌无效时,我会收到 401 响应。

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddDefaultPolicy(builder =>
            {
                builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
            });
        });

        services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o =>
            {
                o.SecurityTokenValidators.Clear();
                o.SecurityTokenValidators.Add(
                    new GoogleTokenValidator(
                        client_id
                        ));
            });
        
        services.AddScoped<PhotoService>();
        services.AddScoped<TagService>();
        services.AddScoped(_ => new BlobServiceClient(Configuration.GetConnectionString("AzureBlobStorage")));
        services.AddDbContext<Data.DataContext>(x => x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        services.AddControllers().AddJsonOptions(options =>
        { …
Run Code Online (Sandbox Code Playgroud)

c# google-authentication jwt bearer-token asp.net-core

0
推荐指数
1
解决办法
4826
查看次数