最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - Authentication failed: method not found - Stack Overflow

programmeradmin3浏览0评论

I am developing the JWT authorization part of my API, and I'm running into an issue where according to the exception stack I'm getting, the header cannot be decoded.

I get the following exceptions:

[Authentication failed]
[1º] Method not found: 'Void Microsoft.IdentityModel.Tokens.Base64UrlEncoder.Decode(System.ReadOnlySpan1<Char>, System.Span1)'.

[2º] IDX14102: Unable to decode the header '[PII of type 'Microsoft.IdentityModel.Logging.SecurityArtifact' is hidden. For more details, see .]' as Base64Url encoded string.

I have checked my package versions, they're listed below. I have tested and re-tested my request.

I am passing Authorization: Bearer <token> in my header.

I have not found a replacement for the decoding portion nor know how should be done.

Any help in this is much appreciated.

This is the service to generate my tokens:

using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Vestis.Configurations;

namespace Vestis.Services;

public class JwtService
{
    private readonly JwtSettings _jwtSettings;

    public JwtService(JwtSettings jwtSettings)
    {
        _jwtSettings = jwtSettings;
    }

    public string GenerateToken(string userId, string userEmail)
    {
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecretKey));
        var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var claims = new List<Claim>
        {
            new Claim(JwtRegisteredClaimNames.Sub, userId),
            new Claim(JwtRegisteredClaimNames.Email, userEmail),
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
        };

        var token = new JwtSecurityToken(
            issuer: _jwtSettings.Issuer,
            audience: _jwtSettings.Audience,
            claims: claims,
            expires: DateTime.UtcNow.AddMinutes(_jwtSettings.ExpirationInMinutes),
            signingCredentials: credentials
        );

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

        // For debugging purposes
        Console.WriteLine($"Generated JWT Token:\n{tokenString}");

        return tokenString;
    }
}

And this is my program setup for the JWT:

void ConfigureJWT()
{
    var jwtSettings = new JwtSettings();
    builder.Configuration.GetSection("JwtSettings").Bind(jwtSettings);
    builder.Services.AddSingleton(jwtSettings);

    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey));

    builder.Services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    }).AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = jwtSettings.Issuer,
            ValidAudience = jwtSettings.Audience,
            IssuerSigningKey = key
        };
        options.Events = new JwtBearerEvents
        {
            OnAuthenticationFailed = context =>
            {
                Console.WriteLine("[Authentication failed]\n" + PrintExceptionStack(context.Exception,out _));
                return Task.CompletedTask;
            },
            OnTokenValidated = context =>
            {
                Console.WriteLine("[Token validated]\n" + context.SecurityToken);
                return Task.CompletedTask;
            }
        };
    });
    builder.Services.AddAuthorization();
}

For reference these are the current package versions I am using (I can see that Microsoft.IdentityModel.Tokens is 1 major version behind, however it is the latest version). All the packages are in their latest versions:

<ItemGroup>
    <PackageReference Include="Humanizer" Version="2.14.1" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.2" />
    <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="9.0.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="9.0.2">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.IdentityModel.Tokens" Version="8.4.0" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="7.2.0" />
</ItemGroup>

I am developing the JWT authorization part of my API, and I'm running into an issue where according to the exception stack I'm getting, the header cannot be decoded.

I get the following exceptions:

[Authentication failed]
[1º] Method not found: 'Void Microsoft.IdentityModel.Tokens.Base64UrlEncoder.Decode(System.ReadOnlySpan1<Char>, System.Span1)'.

[2º] IDX14102: Unable to decode the header '[PII of type 'Microsoft.IdentityModel.Logging.SecurityArtifact' is hidden. For more details, see https://aka.ms/IdentityModel/PII.]' as Base64Url encoded string.

I have checked my package versions, they're listed below. I have tested and re-tested my request.

I am passing Authorization: Bearer <token> in my header.

I have not found a replacement for the decoding portion nor know how should be done.

Any help in this is much appreciated.

This is the service to generate my tokens:

using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Vestis.Configurations;

namespace Vestis.Services;

public class JwtService
{
    private readonly JwtSettings _jwtSettings;

    public JwtService(JwtSettings jwtSettings)
    {
        _jwtSettings = jwtSettings;
    }

    public string GenerateToken(string userId, string userEmail)
    {
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecretKey));
        var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var claims = new List<Claim>
        {
            new Claim(JwtRegisteredClaimNames.Sub, userId),
            new Claim(JwtRegisteredClaimNames.Email, userEmail),
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
        };

        var token = new JwtSecurityToken(
            issuer: _jwtSettings.Issuer,
            audience: _jwtSettings.Audience,
            claims: claims,
            expires: DateTime.UtcNow.AddMinutes(_jwtSettings.ExpirationInMinutes),
            signingCredentials: credentials
        );

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

        // For debugging purposes
        Console.WriteLine($"Generated JWT Token:\n{tokenString}");

        return tokenString;
    }
}

And this is my program setup for the JWT:

void ConfigureJWT()
{
    var jwtSettings = new JwtSettings();
    builder.Configuration.GetSection("JwtSettings").Bind(jwtSettings);
    builder.Services.AddSingleton(jwtSettings);

    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey));

    builder.Services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    }).AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = jwtSettings.Issuer,
            ValidAudience = jwtSettings.Audience,
            IssuerSigningKey = key
        };
        options.Events = new JwtBearerEvents
        {
            OnAuthenticationFailed = context =>
            {
                Console.WriteLine("[Authentication failed]\n" + PrintExceptionStack(context.Exception,out _));
                return Task.CompletedTask;
            },
            OnTokenValidated = context =>
            {
                Console.WriteLine("[Token validated]\n" + context.SecurityToken);
                return Task.CompletedTask;
            }
        };
    });
    builder.Services.AddAuthorization();
}

For reference these are the current package versions I am using (I can see that Microsoft.IdentityModel.Tokens is 1 major version behind, however it is the latest version). All the packages are in their latest versions:

<ItemGroup>
    <PackageReference Include="Humanizer" Version="2.14.1" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.2" />
    <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="9.0.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="9.0.2">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.IdentityModel.Tokens" Version="8.4.0" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="7.2.0" />
</ItemGroup>
Share Improve this question edited Feb 15 at 7:53 marc_s 755k184 gold badges1.4k silver badges1.5k bronze badges asked Feb 14 at 21:49 Jônathas LeandroJônathas Leandro 531 silver badge5 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

A new version of the package, was released with a minor update that fixed this issue. PackageReference Include="Microsoft.IdentityModel.Tokens" Version="8.4.0"

To version 8.5.0

发布评论

评论列表(0)

  1. 暂无评论