forked from microsoft/FeatureManagement-Dotnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHttpContextTargetingContextAccessor.cs
66 lines (56 loc) · 2.22 KB
/
HttpContextTargetingContextAccessor.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
61
62
63
64
65
66
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
//
using Microsoft.AspNetCore.Http;
using Microsoft.FeatureManagement.FeatureFilters;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
namespace FeatureFlagDemo
{
/// <summary>
/// Provides an implementation of <see cref="ITargetingContextAccessor"/> that creates a targeting context using info from the current HTTP request.
/// </summary>
public class HttpContextTargetingContextAccessor : ITargetingContextAccessor
{
private const string TargetingContextLookup = "HttpContextTargetingContextAccessor.TargetingContext";
private readonly IHttpContextAccessor _httpContextAccessor;
public HttpContextTargetingContextAccessor(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
}
public ValueTask<TargetingContext> GetContextAsync()
{
HttpContext httpContext = _httpContextAccessor.HttpContext;
//
// Try cache lookup
if (httpContext.Items.TryGetValue(TargetingContextLookup, out object value))
{
return new ValueTask<TargetingContext>((TargetingContext)value);
}
ClaimsPrincipal user = httpContext.User;
List<string> groups = new List<string>();
//
// This application expects groups to be specified in the user's claims
foreach (Claim claim in user.Claims)
{
if (claim.Type == ClaimTypes.GroupName)
{
groups.Add(claim.Value);
}
}
//
// Build targeting context based off user info
TargetingContext targetingContext = new TargetingContext
{
UserId = user.Identity.Name,
Groups = groups
};
//
// Cache for subsequent lookup
httpContext.Items[TargetingContextLookup] = targetingContext;
return new ValueTask<TargetingContext>(targetingContext);
}
}
}