Reputation: 656
I tried this code for authentication token with firebase and work ok. There is possibility to maintain this for API and the classic Identity for the normal controller? if I add this code the classic identity does not work.
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "xxx";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = "xxx",
ValidateAudience = true,
ValidAudience = "xxx",
ValidateLifetime = true
};
});
Upvotes: 1
Views: 1279
Reputation: 2910
I use .NET Core 3.0 as an example.
Install packages (NuGet): Microsoft.AspNetCore.Authentication.JwtBearer
Update your Controllers to add [Authorize] attribute to your class or method.
Update the Startup class with the following add-ons.
public void ConfigureServices(IServiceCollection services)
{
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "https://securetoken.google.com/my-project-id";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = "https://securetoken.google.com/my-project-id",
ValidateAudience = true,
ValidAudience = "my-project-id",
ValidateLifetime = true
};
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Make the test again on your API, you should have a nice 401 error (unauthorized).
In order to test the API we need a valid token generated by Firebase. The easiest way to do this is use Firebase REST API thanks to the documentation.
To do a log-in with email/password (the ones we created manually before), the URL for the POST request is https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=[API_KEY] and here is an example of request body (obviously change the email and password).
{
"email": "[email protected]",
"password": "mysecretpassword",
"returnSecureToken": "true"
}
You should have a successful reply, assuming you provided with a valid token (limited in time) in the idToken field.
{
"kind": "identitytoolkit#VerifyPasswordResponse",
"localId": "****",
"email": "****",
"displayName": "",
"idToken": "****",
"registered": true,
"refreshToken": "****",
"expiresIn": "3600"
}
Upvotes: 1