Have an Identity user database API with IdentityServer4 and a Blazor client in separate projects. I'm able to register a new user via Postman. When running the code below in the Blazor client (for tinkering and learning)
@page "/registrer"
@using Models
@using System.Net.Http
@using IdentityModel.Client
@inject HttpClient Http
<EditForm Model="@registerUserModel" OnValidSubmit="@HandleValidSubmit">
<DataAnnotationsValidator />
<ValidationSummary />
<InputText id="email" type="email" @bind-Value="@registerUserModel.Email" />
<InputText id="password" type="password" @bind-Value="@registerUserModel.Password" />
<InputText id="confirmPassword" type="password" @bind-Value="@registerUserModel.ConfirmPassword" />
<button type="submit">Registrer deg</button>
</EditForm>
@code {
private RegisterUserModel registerUserModel = new RegisterUserModel();
public async Task HandleValidSubmit()
{
var newUser = new RegisterUserModel
{
Email = registerUserModel.Email,
Password = registerUserModel.Password,
ConfirmPassword = registerUserModel.ConfirmPassword
};
var client = new HttpClient();
var response = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
{
Address = "https://localhost:5001/connect/token",
ClientId = "client",
ClientSecret = "511536EF-F270-4058-80CA-1C89C192F69A",
Scope = "api1"
});
Http.SetBearerToken(response.AccessToken);
await Http.PostJsonAsync("https://localhost:5001/register", newUser);
}
}
I am able to get the access token and validate the Blazor client, but then I get this error
dbug: IdentityServer4.Hosting.CorsPolicyProvider[0] CORS request made for path: /register from origin: http://localhost:60013 but was ignored because path was not for an allowed IdentityServer CORS endpoint
Why? When it works in Postman and there is no CORS policy. Have tried to allow the client with AllowedCorsOrigins
, just to check.
Answer
Browser security prevents a webpage from making requests to a different domain than the one that served the webpage. This restriction is called the same-origin policy. The same-origin policy prevents a malicious site from reading sensitive data from another site. To make requests from the browser to an endpoint with a different origin, the endpoint must enable cross-origin resource sharing (CORS).
And it's not a good idea to store client secrets in an SPA or mobile app as every user is able to see and manipulate all code.