Skip to content

Instantly share code, notes, and snippets.

@cmatskas
Created July 31, 2020 19:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmatskas/e1dc9ddf0ef2137bd7f5e52bd3d9bd04 to your computer and use it in GitHub Desktop.
Save cmatskas/e1dc9ddf0ef2137bd7f5e52bd3d9bd04 to your computer and use it in GitHub Desktop.
using System.Collections.Concurrent;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.Resource;
using Microsoft.Identity.Web.TokenCacheProviders.InMemory;
namespace SecureFeatherHttpApi
{
class Program
{
private static ConcurrentBag<TodoItem> todoItemCollection;
static async Task Main(string[] args)
{
var builder = Microsoft.AspNetCore.Builder.WebApplication.CreateBuilder(args);
builder.Services.AddMicrosoftWebApiAuthentication(builder.Configuration);
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/api/todos", GetTodos).RequireAuthorization();
app.MapPost("api/todos", CreateTodo).RequireAuthorization();
todoItemCollection = new ConcurrentBag<TodoItem>();
await app.RunAsync();
}
static async Task CreateTodo(HttpContext http)
{
http.VerifyUserHasAnyAcceptedScope(new string[] {"access_as_user"});
var todo = await http.Request.ReadJsonAsync<TodoItem>();
todoItemCollection.Add(todo);
http.Response.StatusCode = 204;
}
static async Task GetTodos(HttpContext http)
{
http.VerifyUserHasAnyAcceptedScope(new string[] {"access_as_user"});
if(todoItemCollection.Count == 0)
{
todoItemCollection.Add( new TodoItem{Id = 1, Name = "test", IsComplete = false});
todoItemCollection.Add(new TodoItem{Id=2, Name="hello", IsComplete=true});
}
await http.Response.WriteJsonAsync(todoItemCollection);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment