-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathMeController.cs
More file actions
41 lines (35 loc) · 1.4 KB
/
MeController.cs
File metadata and controls
41 lines (35 loc) · 1.4 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
using System.Net.Mime;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using SimpleAuthentication.ApiKey;
namespace ApiKeySample.Controllers;
[ApiController]
[Route("api/[controller]")]
[Produces(MediaTypeNames.Application.Json)]
public class MeController : ControllerBase
{
[Authorize]
[HttpGet]
[ProducesResponseType<User>(StatusCodes.Status200OK)]
[ProducesDefaultResponseType]
public ActionResult<User> Get(IOptions<ApiKeySettings> apiKeySettingsOptions)
{
// Get roles using the configured role claim type from options (default is ClaimTypes.Role)
var roles = User.FindAll(apiKeySettingsOptions.Value.RoleClaimType).Select(c => c.Value);
return new User(User.Identity!.Name, roles);
}
[Authorize(Roles = "Administrator")]
[HttpGet("administrator")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[EndpointDescription("This endpoint requires the user to have the 'Administrator' role")]
public IActionResult AdministratorOnly()
=> NoContent();
[Authorize(Roles = "User")]
[HttpGet("user")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[EndpointDescription("This endpoint requires the user to have the 'User' role")]
public IActionResult UserOnly()
=> NoContent();
}
public record class User(string? UserName, IEnumerable<string> Roles);