Hi,@Enrico Rossini
The Authentication Scheme IdentityConstants.ApplicationScheme
is based on cookie ,to protect api endpoints, we usually use token based authentication scheme
Based on the codes in this document:
//replace the service
builder.Services.AddIdentityApiEndpoints<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddSignInManager()
.AddDefaultTokenProviders();
//builder.Services.AddIdentityCore<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
// .AddEntityFrameworkStores<ApplicationDbContext>()
// .AddSignInManager()
//.AddDefaultTokenProviders()
//.AddApiEndpoints();
//builder.Services.AddIdentityApiEndpoints<ApplicationUser>();
replace the route mapping middleware:
app.MapIdentityApi<ApplicationUser>();
//app.MapAdditionalIdentityEndpoints();
modify the scheme for api endpoints:
public static void MapClientEndpoints(this IEndpointRouteBuilder routes)
{
var group = routes.MapGroup("/api/Client").WithTags("Client");
group.MapGet("/", async (HttpContext context) =>
{
return Results.Ok("apicontent");
})
.RequireAuthorization(p =>
{
p.AuthenticationSchemes = new List<string>() { IdentityConstants.BearerScheme };
p.RequireAuthenticatedUser();
})
.WithName("GetAllClients")
.WithOpenApi();
}
When you succeed login,acquire an access token and store it somewhere,(you could modify codes in Login Component to avoid sending httprequest):
var loginItemJson = new StringContent(
JsonSerializer.Serialize(new
{
email = Input.Email,
password = Input.Password
}),
Encoding.UTF8,
Application.Json);
var httpclient = factory.CreateClient("MyClient");
using var httpResponseMessage =
await httpclient.PostAsync("/login", loginItemJson);
var tokenstr = await httpResponseMessage.Content.ReadAsStringAsync();
var accesstoken = JsonSerializer.Deserialize<tokenModel>(tokenstr)?.accessToken;
accesstokenContainer.SetToken(accesstoken);
Append the Authorization Header when you send request to your api endpoints:
var httpclient = httpclientfactory.CreateClient("MyClient");
var accesstoken = accesstokenContainer.TryGetToken();
httpclient.DefaultRequestHeaders.Add(
"Authorization", "Bearer " + accesstoken);
var responsemessage = await httpclient.GetAsync("/api/Client");
var contenet = responsemessage.Content.ReadAsStringAsync();
Now it succeed :
If you want to use cookie based authentication,you may follow this document
Best regards,
Ruikai Feng