Skip to content

Commit

Permalink
Add cors to fake authentication server (#33)
Browse files Browse the repository at this point in the history
  • Loading branch information
OlegRakovich authored Apr 26, 2023
1 parent 19eba78 commit 2a58b36
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
3 changes: 2 additions & 1 deletion code/backend/.vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@
"stopAtEntry": false,
"env": {
"ASPNETCORE_ENVIRONMENT": "Development",
"ASPNETCORE_URLS": "http://localhost:5002"
"ASPNETCORE_URLS": "http://localhost:5002",
"CrossOriginDomains": "http://localhost:5000"
}
}
],
Expand Down
26 changes: 26 additions & 0 deletions code/backend/Server.Users.Fake/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

var app = builder.Build();

app.Use(Cors);

app.MapGet("/login", (string redirect_uri, string response_type, string scope) =>
{
if (response_type != "code") return InvalidResponseType();
Expand Down Expand Up @@ -80,6 +82,30 @@ static IResult InvalidRequestUri(AuthenticationRequest request, string redirect_
static IResult BadRequest(string message)
=> Results.BadRequest(new { message = message });

static Task Cors(HttpContext context, Func<Task> next)
{
if (!context.Request.Headers.Origin.Any()) return next();

var origin = context.Request.Headers.Origin.Single();
if (AllowedOrigins().Contains(origin))
{
context.Response.Headers["Access-Control-Allow-Origin"] = origin;
}
context.Response.Headers["Access-Control-Allow-Headers"] = "content-type, accept, origin, authorization";
context.Response.Headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS";

if (context.Request.Method != "OPTIONS") return next();

context.Response.StatusCode = 200;
return context.Response.CompleteAsync();
}

static string[] AllowedOrigins()
=> Configuration("CrossOriginDomains").Split(',');

static string Configuration(string name)
=> Environment.GetEnvironmentVariable(name) ?? throw new NullReferenceException($"Environment varialbe {name} is not set");

class LoginRequest
{
public string redirect_uri { get; init; } = string.Empty;
Expand Down

0 comments on commit 2a58b36

Please sign in to comment.