-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
78 lines (63 loc) · 2.87 KB
/
Copy pathProgram.cs
File metadata and controls
78 lines (63 loc) · 2.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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.Graph;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.Resource;
using Microsoft.Identity.Web.TokenCacheProviders.InMemory;
namespace SecureFeatherHttpApi
{
class Program
{
private static ConcurrentBag<TodoItem> todoItemCollection;
private static string[] scopes = new string[] {"user.read"};
static async Task Main(string[] args)
{
var builder = Microsoft.AspNetCore.Builder.WebApplication.CreateBuilder(args);
builder.Services.AddMicrosoftWebApiAuthentication(builder.Configuration)
.AddMicrosoftWebApiCallsWebApi(builder.Configuration)
.AddInMemoryTokenCaches();
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/api/todos", GetTodos).RequireAuthorization();
app.MapPost("api/todos", CreateTodo).RequireAuthorization();
app.MapGet("/api/me", GetGraphData).RequireAuthorization();
todoItemCollection = new ConcurrentBag<TodoItem>();
await app.RunAsync();
}
static async Task CreateTodo(HttpContext http)
{
http.VerifyUserHasAnyAcceptedScope(scopes);
var todo = await http.Request.ReadJsonAsync<TodoItem>();
todoItemCollection.Add(todo);
http.Response.StatusCode = 204;
}
static async Task GetTodos(HttpContext http)
{
http.VerifyUserHasAnyAcceptedScope(scopes);
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);
}
static async Task GetGraphData(HttpContext http)
{
http.VerifyUserHasAnyAcceptedScope(scopes);
var tokenAcquisition = http.RequestServices.GetRequiredService<ITokenAcquisition>();
var authProvider = new DelegateAuthenticationProvider(async x => {
var accessToken = await tokenAcquisition.GetAccessTokenForUserAsync(new string[] {"User.Read"});
x.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
});
var graphClient = new GraphServiceClient(authProvider);
var me = await graphClient.Me.Request().GetAsync();
await http.Response.WriteJsonAsync(new {Name = me.GivenName, Email= me.Mail});
}
}
}