This repository has been archived by the owner on Sep 2, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
/
SimpleAuthorizeAttribute.cs
49 lines (43 loc) · 1.82 KB
/
SimpleAuthorizeAttribute.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
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Web.Http;
using System.Web.Http.Controllers;
namespace YellowNotes.Api.Attributes
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
internal class SimpleAuthorizeAttribute : AuthorizeAttribute
{
public string Devices { get; set; } = string.Empty;
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized,
"CUSTOM: Authorization has been denied for this request");
}
protected override bool IsAuthorized(HttpActionContext actionContext)
{
var baseIsAuthorized = base.IsAuthorized(actionContext);
if (!baseIsAuthorized)
{
return false;
}
var simpleAuthorizeAttribute =
actionContext.ActionDescriptor.GetCustomAttributes<SimpleAuthorizeAttribute>(false).FirstOrDefault() ??
actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<SimpleAuthorizeAttribute>(true).FirstOrDefault();
if (simpleAuthorizeAttribute == null)
{
return true;
}
var allowedDevices = simpleAuthorizeAttribute.Devices.Split(new char[','], StringSplitOptions.RemoveEmptyEntries);
if (allowedDevices.Length < 1)
{
return true;
}
var claimsIdentity = actionContext.RequestContext.Principal.Identity as ClaimsIdentity;
string device = claimsIdentity.FindFirst(ApiConstants.ClaimDevice).Value;
return allowedDevices.Contains(device);
}
}
}