Repository navigation
Expand file tree
/
Copy pathClaim.cs
More file actions
72 lines (60 loc) · 2.69 KB
/
Copy pathClaim.cs
File metadata and controls
72 lines (60 loc) · 2.69 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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Reflection;
namespace System.Web.Helpers.Claims
{
// Represents a Claim; serves as an abstraction around the WIF SDK and 4.5 Claim types since
// we can't compile directly against them.
internal sealed class Claim
{
public Claim(string claimType, string value)
{
ClaimType = claimType;
Value = value;
}
public string ClaimType { get; private set; }
public string Value { get; private set; }
// Creates a Claim from a TClaim object (duck typing).
//
// The TClaim must have the following shape:
// class TClaim {
// string ClaimType { get; } // or just 'Type'
// string Value { get; }
// }
internal static Claim Create<TClaim>(TClaim claim)
{
return ClaimFactory<TClaim>.Create(claim);
}
private static class ClaimFactory<TClaim>
{
private static readonly Func<TClaim, string> _claimTypeGetter = CreateClaimTypeGetter();
private static readonly Func<TClaim, string> _valueGetter = CreateValueGetter();
public static Claim Create(TClaim claim)
{
return new Claim(_claimTypeGetter(claim), _valueGetter(claim));
}
private static Func<TClaim, string> CreateClaimTypeGetter()
{
// the claim type might go by one of two different property names
return CreateGeneralPropertyGetter("ClaimType") ?? CreateGeneralPropertyGetter("Type");
}
private static Func<TClaim, string> CreateGeneralPropertyGetter(string propertyName)
{
PropertyInfo propInfo = typeof(TClaim).GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance, null, typeof(string), Type.EmptyTypes, null);
if (propInfo == null)
{
return null;
}
MethodInfo propGetter = propInfo.GetGetMethod();
// For improved perf, instance methods can be treated as static methods by leaving
// the 'this' parameter unbound. Virtual dispatch for the property getter will
// still take place as expected.
return (Func<TClaim, string>)Delegate.CreateDelegate(typeof(Func<TClaim, string>), propGetter);
}
private static Func<TClaim, string> CreateValueGetter()
{
return CreateGeneralPropertyGetter("Value");
}
}
}
}