I am new to web api and trying the Authorization for my API but right now i'm stuck with Authorization Error that my sent Token is not Valid it has been ac couple of days and still not sure what is the problem
my program.cs
using ETA.Website.API.Helpers;
using ETA.Website.API.Extentions;
using ETA.Website.Data;
using ETA.Website.Data.Models;
using ETA.Website.Infrasructure.UnitOfWork.File;
using ETA.Website.Infrasructure.UnitOfWork.UserManagment;
using ETA.Website.Infrastructure.Helpers;
using ETA.Website.Infrastructure.Repository;
using ETA.Website.Infrastructure.Repository.Interfaces;
using ETA.Website.Infrastructure.UnitOfWork.AdminPanel;
using ETA.Website.Infrastructure.UnitOfWork.Identity;
using ETA.Website.Infrastructure.UnitOfWork.Messaging;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.FileProviders;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Filters;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
var Configration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
var _config = Configration.Build();
builder.Services.Configure<JwtSettings>(_config.GetSection("JsonWebTokenKeys"));
builder.Services.AddJWTTokenServices(builder.Configuration);
builder.Services.AddTransient<IRepositoryProvider, RepositoryProvider>();
builder.Services.AddTransient<IRepositoryFactory, RepositoryFactory>();
builder.Services.AddTransient<IIdentityServiceUOW, IdentityServiceUOW>();
builder.Services.AddTransient<IMessagingServiceUOW, MessagingServiceUOW>();
builder.Services.AddTransient<IAdminPanelServiceUOW, AdminPanelServiceUOW>();
builder.Services.AddTransient<IUserManagmentUOW, UserManagmentUOW>();
builder.Services.AddTransient<IFileUOW, FileUOW>();
builder.Services.AddSingleton<IEncryption, Encryption>();
builder.Services.AddAutoMapper(typeof(AutoMapperProfiles).Assembly);
builder.Services.AddTransient<DbContext, WebsiteContext>();
builder.Services.AddDbContext<WebsiteContext>(options => options.UseSqlServer(_config.GetConnectionString("WebsiteDB"), b => b.MigrationsAssembly("ETA.Website.API")));
builder.Services.Configure<FormOptions>(o =>
{
o.ValueLengthLimit = int.MaxValue;
o.MultipartBodyLengthLimit = int.MaxValue;
o.MemoryBufferThreshold = int.MaxValue;
});
builder.Services.AddSwaggerGen(options => {
options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Description = "Standard Authorization header using the Bearer scheme (\"bearer {token}\")",
In = ParameterLocation.Header,
Name = "Authorization",
Type = SecuritySchemeType.ApiKey
});
options.OperationFilter<SecurityRequirementsOperationFilter>();
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(c => {
c.SwaggerEndpoint("/swagger/v1/swagger.json", "API V");
c.RoutePrefix = String.Empty;
}
);
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.UseCors(builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new
PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"Resources")),
RequestPath = new PathString("/Resources")
});
app.Run();
and my AddAuthentecationService
public static class AddJWTTokenServicesExtensions
{
public static void AddJWTTokenServices(this IServiceCollection Services, IConfiguration Configuration)
{
// Add Jwt Setings
var bindJwtSettings = new JwtSettings();
Configuration.Bind("JsonWebTokenKeys", bindJwtSettings);
Services.AddSingleton(bindJwtSettings);
Services.AddAuthentication(options => {
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options => {
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
{
ValidateIssuerSigningKey = bindJwtSettings.ValidateIssuerSigningKey,
IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(bindJwtSettings.IssuerSigningKey)),
ValidateIssuer = bindJwtSettings.ValidateIssuer,
ValidIssuer = bindJwtSettings.ValidIssuer,
ValidateAudience = bindJwtSettings.ValidateAudience,
ValidAudience = bindJwtSettings.ValidAudience,
RequireExpirationTime = bindJwtSettings.RequireExpirationTime,
ValidateLifetime = bindJwtSettings.RequireExpirationTime,
ClockSkew = TimeSpan.FromDays(1),
};
});
}
}
and my Create Token Function
public string CreateToken(User user)
{
List<Claim> claims = new List<Claim>
{
new Claim(ClaimTypes.Role, user.Type),
new Claim(ClaimTypes.Name, user.FullName),
new Claim(ClaimTypes.Email, user.Email),
new Claim(ClaimTypes.Expiration, DateTime.UtcNow.AddDays(1).ToString("MMM ddd dd yyyy HH:mm:ss tt"))
};
// Get secret key
var key = System.Text.Encoding.ASCII.GetBytes(_jwtsettings.Value.IssuerSigningKey);
Guid Id = Guid.Empty;
DateTime expireTime = DateTime.UtcNow.AddDays(1);
var JWToken = new JwtSecurityToken(issuer: _jwtsettings.Value.ValidIssuer, audience: _jwtsettings.Value.ValidAudience, claims: claims, notBefore: new DateTimeOffset(DateTime.Now).DateTime, expires: new DateTimeOffset(expireTime).DateTime, signingCredentials: new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256));
return new JwtSecurityTokenHandler().WriteToken(JWToken);
}
a controller that i am testing on
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ETA.Website.API.Controllers
{
[ApiController]
[Route("[controller]")]
[Authorize(AuthenticationSchemes = Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerDefaults.AuthenticationScheme)]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}
if there is anything else that might help please share