This repository has been archived by the owner on Dec 13, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 600
/
ClaimsAuthorizationRequirement.cs
74 lines (68 loc) · 3.07 KB
/
ClaimsAuthorizationRequirement.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
67
68
69
70
71
72
73
74
// 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;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Internal;
namespace Microsoft.AspNetCore.Authorization.Infrastructure
{
/// <summary>
/// Implements an <see cref="IAuthorizationHandler"/> and <see cref="IAuthorizationRequirement"/>
/// which requires at least one instance of the specified claim type, and, if allowed values are specified,
/// the claim value must be any of the allowed values.
/// </summary>
public class ClaimsAuthorizationRequirement : AuthorizationHandler<ClaimsAuthorizationRequirement>, IAuthorizationRequirement
{
/// <summary>
/// Creates a new instance of <see cref="ClaimsAuthorizationRequirement"/>.
/// </summary>
/// <param name="claimType">The claim type that must be present.</param>
/// <param name="allowedValues">The optional list of claim values, which, if present,
/// the claim must match.</param>
public ClaimsAuthorizationRequirement(string claimType, IEnumerable<string> allowedValues)
{
if (claimType == null)
{
throw new ArgumentNullException(nameof(claimType));
}
ClaimType = claimType;
AllowedValues = allowedValues;
}
/// <summary>
/// Gets the claim type that must be present.
/// </summary>
public string ClaimType { get; }
/// <summary>
/// Gets the optional list of claim values, which, if present,
/// the claim must match.
/// </summary>
public IEnumerable<string> AllowedValues { get; }
/// <summary>
/// Makes a decision if authorization is allowed based on the claims requirements specified.
/// </summary>
/// <param name="context">The authorization context.</param>
/// <param name="requirement">The requirement to evaluate.</param>
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, ClaimsAuthorizationRequirement requirement)
{
if (context.User != null)
{
var found = false;
if (requirement.AllowedValues == null || !requirement.AllowedValues.Any())
{
found = context.User.Claims.Any(c => string.Equals(c.Type, requirement.ClaimType, StringComparison.OrdinalIgnoreCase));
}
else
{
found = context.User.Claims.Any(c => string.Equals(c.Type, requirement.ClaimType, StringComparison.OrdinalIgnoreCase)
&& requirement.AllowedValues.Contains(c.Value, StringComparer.Ordinal));
}
if (found)
{
context.Succeed(requirement);
}
}
return TaskCache.CompletedTask;
}
}
}