Skip to content

Instantly share code, notes, and snippets.

@andrelashley
Forked from edijer/Startup.cs
Created December 13, 2023 03:32
Show Gist options
  • Save andrelashley/27ae1218597eff028ad440e251fad920 to your computer and use it in GitHub Desktop.
Save andrelashley/27ae1218597eff028ad440e251fad920 to your computer and use it in GitHub Desktop.
Setting up API authentication using Firebase JWT tokens in ASP.NET Core 3.1.
const apiCall = async (user) => {
try {
const response = await fetch("https://localhost/api/v1/data", {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json;charset=UTF-8",
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${user.jwtToken}`,
},
});
const data = await response.json();
console.log(data);
} catch (error) {
console.log(error);
}
}
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
namespace Reference.WebApi
{
// Dependency: Microsoft.AspNetCore.Authentication.JwtBearer (3.1.4 at time of writing)
public class Startup
{
private const string CORS_POLICY_KEY = "CorsPolicyKey";
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)
{
// Firebase Authentication
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
var projectId = "your-firebase-project-id";
options.Authority = $"https://securetoken.google.com/{projectId}";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = $"https://securetoken.google.com/{projectId}",
ValidateAudience = true,
ValidAudience = projectId,
ValidateLifetime = true
};
});
// CORS Setup Options
services.AddCors(options =>
{
options.AddPolicy(name: CORS_POLICY_KEY, builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
services.AddControllers();
}
// 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();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(CORS_POLICY_KEY);
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;
namespace Reference.WebApi.Controllers
{
[Authorize]
[ApiController]
public class TestApiController : ControllerBase
{
private readonly ILogger<TestApiController> _logger;
public TestApiController(ILogger<TestApiController> logger)
{
_logger = logger;
}
[HttpGet("api/v1/data")]
public async Task<JsonResult> Get()
{
throw new NotImplementedException();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment