When I'm trying to get authorized information by using provided bearer token it shows a 401 unauthorized error. The console shows

Bearer was not authenticated. Failure message: No SecurityTokenValidator available for token: Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InNoYWZmYXRAZ21haWwuY29tIiwibmJmIjoxNjIxMTg3ODYyLCJleHAiOjE2MjE3OTI2NjIsImlhdCI6MTYyMTE4Nzg2Mn0.qVULLqV4TmduJalzuLGHyVyDSXokaCHggeb6Rn9aGCzPmG4yS_LaxmUg2jdKAPIOXkAkHvpk6KLT5meIuCcZig

info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]

Authorization failed. These requirements were not met:
DenyAnonymousAuthorizationRequirement: Requires an authenticated user.

Code:

public static class IdentityServiceExtensions
{
        public static IServiceCollection AddIdentityServices(this IServiceCollection services, IConfiguration config)
        {
            var builder = services.AddIdentityCore<ApplicationUser>();
            builder = new IdentityBuilder(builder.UserType, builder.Services);
            builder.AddEntityFrameworkStores<ApplicationDbContext>();
            builder.AddSignInManager<SignInManager<ApplicationUser>>();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(option =>
                {
                    option.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["Token:Key"])),
                        //ValidIssuer = config["Token:Issuer"],
                        ValidateIssuer = false,
                        ValidateAudience = false,
                        ClockSkew = TimeSpan.Zero


                    };
                });
            return services;
        }
}

public class TokenService : ITokenService
{
    private readonly IConfiguration _config;
    private readonly SymmetricSecurityKey _key;

    public TokenService(IConfiguration config)
    {
        _config = config;
        _key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Token:Key"]));
    }

    public string CreateToken(ApplicationUser user)
    {
        var claims = new List<Claim>
        {
            new Claim(JwtRegisteredClaimNames.Email, user.Email),
            //new Claim(JwtRegisteredClaimNames.GivenName, user.FullName)
        };

        var creds = new SigningCredentials(_key, SecurityAlgorithms.HmacSha512Signature);

        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(claims),
            Expires = DateTime.Now.AddDays(7),
            SigningCredentials = creds,
            //Issuer = _config["Token:Issuer"]
        };

        var tokenHandler = new JwtSecurityTokenHandler();
        var token = tokenHandler.CreateToken(tokenDescriptor);

        return tokenHandler.WriteToken(token);
    }
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
        services.AddControllers();
        services.AddDbContext<ApplicationDbContext>(options =>
                        options.UseSqlServer(Configuration.GetConnectionString("MvcMovieContext")));
        services.AddScoped<IBranchRepository, BranchRepository>();
        services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
        //Identity Service Extensions Added Here...........
        services.AddIdentityServices(Configuration);

        //Token Service registered here [Dependency Injection Purpose]
        services.AddScoped<ITokenService, TokenService>();

        //This service Need For Angular verification.........
        services.AddCors(options =>
        {
            options.AddPolicy(MyAllowSpecificOrigins,
            builder =>
            {
                builder.WithOrigins("http://localhost:4200")
                       .AllowAnyHeader()
                       .AllowAnyMethod();
            });
        });

        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "HospitalAPI", Version = "v1" });
        });
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "HospitalAPI v1"));
        }
        app.UseCors(MyAllowSpecificOrigins);
        app.UseRouting();

        
        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
}
0

There are 0 best solutions below