-
Notifications
You must be signed in to change notification settings - Fork 11
/
AuthInfoExtensions.cs
60 lines (57 loc) · 2.29 KB
/
AuthInfoExtensions.cs
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
using System;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Threading.Tasks;
namespace FunctionWithAuth
{
public static class AuthInfoExtensions
{
private static HttpClient _httpClient = new HttpClient(); // cache and reuse to avoid repeated creation on Function calls
/// <summary>
/// Find a claim of the specified type
/// </summary>
/// <param name="authInfo"></param>
/// <param name="claimType"></param>
/// <returns></returns>
public static AuthUserClaim GetClaim(this AuthInfo authInfo, string claimType)
{
return authInfo.UserClaims.FirstOrDefault(c => c.Type == claimType);
}
/// <summary>
/// Get the EasyAuth properties for the currently authenticated user
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public static async Task<AuthInfo> GetAuthInfoAsync(this HttpRequestMessage request)
{
string zumoAuthToken = request.GetZumoAuthToken();
if (string.IsNullOrEmpty(zumoAuthToken))
{
return null;
}
var authMeRequest = new HttpRequestMessage(HttpMethod.Get, GetEasyAuthEndpoint())
{
Headers =
{
{ "X-ZUMO-AUTH", zumoAuthToken }
}
};
var response = await _httpClient.SendAsync(authMeRequest);
var authInfoArray = await response.Content.ReadAsAsync<AuthInfo[]>();
return authInfoArray.Length >= 1 ? authInfoArray[0] : null; // The .auth/me content is a single item array if it is populated
}
private static string GetEasyAuthEndpoint()
{
// Get the hostname from environment variables so that we don't need config - thank you App Service!
var hostname = Environment.GetEnvironmentVariable("WEBSITE_HOSTNAME");
// Build up the .auth/me url
string requestUri = $"https://{hostname}/.auth/me";
return requestUri;
}
private static string GetZumoAuthToken(this HttpRequestMessage req)
{
return req.Headers.GetValues("X-ZUMO-AUTH").FirstOrDefault();
}
}
}