-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValuesController.cs
More file actions
97 lines (90 loc) · 2.86 KB
/
ValuesController.cs
File metadata and controls
97 lines (90 loc) · 2.86 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Security.Claims;
namespace SimpleJwt4Core22.Controllers
{
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly JsonSerializerSettings _serializerSettings;
public ValuesController()
{
_serializerSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
}
// GET api/values
[HttpGet]
public IActionResult Get()
{
return handleRequest();
}
// All of these endpoints do the same thing except for the
// authorized roles
[Route("admin")]
[Authorize(Policy = "AdminPolicy")]
[HttpGet]
public IActionResult GetAdmin()
{
return handleRequest();
}
[Route("super")]
[Authorize(Policy = "SuperPolicy")]
[HttpGet]
public IActionResult GetSuper()
{
return handleRequest();
}
[Route("either")]
[Authorize(Policy = "EitherPolicy")]
[HttpGet]
public IActionResult GetBoth()
{
return handleRequest();
}
[Route("open")]
[AllowAnonymous]
[HttpGet]
public IActionResult GetOpen()
{
return handleRequest();
}
private IActionResult handleRequest()
{
// Read the claims that I wrote in JwtController:
var claims = ((ClaimsIdentity)User.Identity).Claims;
var id = getClaimByType(claims, "id");
var name = getClaimByType(claims, "name");
// In JwtController, I created a claim for "role" so I would expect this to have a value:
var role = getClaimByType(claims, "role");
// however, by magic, this one has the value:
var msRole = getClaimByType(claims, "http://schemas.microsoft.com/ws/2008/06/identity/claims/role");
var response = new
{
id,
name,
role,
msRole
};
// Send the claims back in the Response:
var json = JsonConvert.SerializeObject(response, _serializerSettings);
return new OkObjectResult(json);
}
public static string getClaimByType(IEnumerable<Claim> jwt, string typeKey)
{
foreach (var claim in jwt)
{
if (claim.Type == typeKey)
{
return claim.Value;
}
}
return string.Empty;
}
}
}