I am working on dotnet core API. I can generate the token and also checked the token with this site jwt.ms. Everything is working fine. But when I send a request with this token it says(please check the image)
.
Startup.cs
namespace blogapi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(x => x
.UseMySql(Configuration.GetConnectionString("DefaultConnection"))
.ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.IncludeIgnoredWarning)));
services.AddCors();
//services.AddControllers();
services.AddScoped<IPostRepository, PostRepository>();
services.AddScoped<IUserRepository, UserRepository>();
services.AddAutoMapper(typeof(Maps));
// services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
// {
// builder.AllowAnyOrigin()
// .AllowAnyMethod()
// .AllowAnyHeader();
// }));
var appSettingsSection = Configuration.GetSection("AppSettings");
services.Configure<AppSettings>(appSettingsSection);
// configure jwt authentication
var appSettings = appSettingsSection.Get<AppSettings>();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
// x.Events = new JwtBearerEvents
// {
// OnTokenValidated = context =>
// {
// var userService = context.HttpContext.RequestServices.GetRequiredService<IUserRepository>();
// var userId = int.Parse(context.Principal.Identity.Name);
// var user = userService.GetById(userId);
// if (user == null)
// {
// // return unauthorized if user no longer exists
// context.Fail("Unauthorized");
// }
//
// return Task.CompletedTask;
// }
// };
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key: key),
ValidateIssuer = false,
ValidateAudience = false,
RequireExpirationTime = false,
ValidateLifetime = true
// ValidateIssuerSigningKey = true,
// IssuerSigningKey = new SymmetricSecurityKey(key),
// ValidateIssuer = false,
// ValidateAudience = false
};
});
//services.AddControllersWithViews();
services.AddMvc(options => options.EnableEndpointRouting = false);
}
// 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();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
app.UseHttpsRedirection();
}
app.UseStaticFiles();
// app.UseRouting();
//
// //app.UseCors(builder => builder.WithOrigins("http://localhost:4200"));
// app.UseCors("MyPolicy");
//
// app.UseAuthorization();
//
// app.UseEndpoints(endpoints =>
// {
// endpoints.MapControllerRoute(
// name: "default",
// pattern: "{controller=Home}/{action=Index}/{id?}");
// });
//app.UseRouting();
// global cors policy
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseAuthentication();
app.UseAuthorization();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
//app.UseEndpoints(endpoints => endpoints.MapControllers());
}
}
}
PostController.cs
namespace blogapi.Controllers.Api
{
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Route("api/[controller]")]
[ApiController]
public class PostController : ControllerBase
{
private readonly IPostRepository _repo;
private readonly IUserRepository _userRepository;
private readonly IMapper _mapper;
public PostController(IPostRepository repo, IMapper mapper, IUserRepository userRepository)
{
_repo = repo;
_mapper = mapper;
_userRepository = userRepository;
}
// GET api/post
[AllowAnonymous]
[HttpGet]
public IEnumerable<PostViewModel> GetPosts()
{
var posts = _repo.FindAll().ToList();
var model = _mapper.Map<List<Post>, List<PostViewModel>>(posts);
return model;
}
User GetSecureUser()
{
var id = int.Parse(HttpContext.User.Claims.First().Value);
return _userRepository.GetById(id);
}
// POST api/post
[HttpPost]
public CreatePostRequest AddPost([FromBody] CreatePostRequest postRequest)
{
var post = new Post
{
Title = postRequest.Title,
Description = postRequest.Description,
UserId = HttpContext.GetCurrentUserId()
};
//_repo.Create(post);
return postRequest;
}
[AllowAnonymous]
// GET api/post/{id}
[HttpGet("{id}")]
public Post GetPost(int id)
{
return _repo.FindById(id);
}
}
}
I tried the solution given from this link already but couldn't figure out. Any help would be appreciated.
Sample token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJydW1pQGdtYWlsLmNvbSIsIklkIjoiMSIsIm5iZiI6MTU4MDI4NjA5NiwiZXhwIjoxNTgwNTQ1Mjk2LCJpYXQiOjE1ODAyODYwOTZ9.G-9e2uNzBcznazaII1_p5EVjtKtVES6XalXPEnlef6c