I cannot reach the authorized url even I log in and send my token from web ui. But I can reach data by using postman or swagger.
I log in system and get token and then send request from web ui to api but then get error says : InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action configureOptions).
In the code belows, I can see the token in session so token is adding in session correctly.
[HttpPost]
public async Task<IActionResult> Index(LoginUserDto dto)
{
if (ModelState.IsValid)
{
var client = _httpClientFactory.CreateClient();
var jsonData = JsonConvert.SerializeObject(dto);
StringContent stringContent = new StringContent(jsonData,Encoding.UTF8,"application/json");
var response = await client.PostAsync("http://localhost:10881/api/Token",stringContent);
if (response.IsSuccessStatusCode)
{
var token = await response.Content.ReadAsStringAsync();
HttpContext.Session.SetString("AuthToken", token);
var token2 = HttpContext.Session.GetString("AuthToken");
return RedirectToAction("Index", "Staff");
}
else
{
ModelState.AddModelError(string.Empty, "Giriş başarısız. Lütfen tekrar deneyin.");
}
}
return View();
}
Inbox request :
public async Task<IActionResult> Inbox()
{
var token = HttpContext.Session.GetString("AuthToken");
if (string.IsNullOrEmpty(token))
{
return Unauthorized();
}
var client = _httpClientFactory.CreateClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var response = await client.PostAsync("http://localhost:10881/InboxList", null);
if (response.IsSuccessStatusCode)
{
var jsonData = await response.Content.ReadAsStringAsync();
var values = JsonConvert.DeserializeObject<List<InboxContactDto>>(jsonData);
var contactCount = await GetContactCount();
ViewBag.ContactCount = contactCount;
ViewBag.SendMessageCount = await GetSendMessageCount();
return View(values);
}
else
{
Console.WriteLine("Yetkisiz erişim: " + response.StatusCode);
}
return View();
}
program.cs:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});
// Add custom application services
builder.Services.AddApplicationServices();
// Configure DbContext with SQL Server
builder.Services.AddDbContext<Context>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
// Configure Identity services
builder.Services.AddIdentity<AppUser, AppRole>().AddEntityFrameworkStores<Context>();
// Configure JWT Authentication
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidIssuer = "http://localhost",
ValidAudience = "http://localhost",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("aspnetcoreapiapiapiherzamanheryerdeenbuyukfener")),
ValidateIssuerSigningKey = true,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
});
// Add AutoMapper
builder.Services.AddAutoMapper(typeof(Program));
// Configure CORS
builder.Services.AddCors(opt =>
{
opt.AddPolicy("OtelApiCors", opts =>
{
opts.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
});
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "HotelProject.WebApi v1");
c.RoutePrefix = "";
});
}
app.UseCors("OtelApiCors");
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();