Skip to content

Commit c80526e

Browse files
committed
Add role-based authorization to MeController
Updated MeController to include role-based authorization by modifying the Get method to accept role settings and return user roles. Added AdministratorOnly and UserOnly endpoints with role-based access. Updated User record to include roles. Extended appsettings.json for role configuration. Adjusted Program.cs for new authorization requirements.
1 parent 6fcbac8 commit c80526e

9 files changed

Lines changed: 67 additions & 17 deletions

File tree

samples/Controllers/ApiKeySample/Controllers/MeController.cs

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
using System.Net.Mime;
22
using Microsoft.AspNetCore.Authorization;
33
using Microsoft.AspNetCore.Mvc;
4+
using Microsoft.Extensions.Options;
5+
using SimpleAuthentication.ApiKey;
46

57
namespace ApiKeySample.Controllers;
68

@@ -13,8 +15,27 @@ public class MeController : ControllerBase
1315
[HttpGet]
1416
[ProducesResponseType<User>(StatusCodes.Status200OK)]
1517
[ProducesDefaultResponseType]
16-
public ActionResult<User> Get()
17-
=> new User(User.Identity!.Name);
18+
public ActionResult<User> Get(IOptions<ApiKeySettings> apiKeySettingsOptions)
19+
{
20+
// Get roles using the configured role claim type from options (default is ClaimTypes.Role)
21+
var roles = User.FindAll(apiKeySettingsOptions.Value.RoleClaimType).Select(c => c.Value);
22+
23+
return new User(User.Identity!.Name, roles);
24+
}
25+
26+
[Authorize(Roles = "Administrator")]
27+
[HttpGet("administrator")]
28+
[ProducesResponseType(StatusCodes.Status204NoContent)]
29+
[EndpointDescription("This endpoint requires the user to have the 'Administrator' role")]
30+
public IActionResult AdministratorOnly()
31+
=> NoContent();
32+
33+
[Authorize(Roles = "User")]
34+
[HttpGet("user")]
35+
[ProducesResponseType(StatusCodes.Status204NoContent)]
36+
[EndpointDescription("This endpoint requires the user to have the 'User' role")]
37+
public IActionResult UserOnly()
38+
=> NoContent();
1839
}
1940

20-
public record class User(string? UserName);
41+
public record class User(string? UserName, IEnumerable<string> Roles);

samples/Controllers/ApiKeySample/appsettings.json

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,23 @@
66
// You can specify either HeaderName, QueryStringKey or both
77
"HeaderName": "x-api-key",
88
"QueryStringKey": "code",
9+
//"NameClaimType": "user_name", // Default: http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name
10+
//"RoleClaimType": "user_role", // Default: http://schemas.microsoft.com/ws/2008/06/identity/claims/role
911
// You can set a fixed API Key for authentication. If you have a single value, you can just use the plain property:
1012
"ApiKeyValue": "f1I7S5GXa4wQDgLQWgz0",
1113
"UserName": "ApiUser", // Required if ApiKeyValue is used
14+
"Roles": [ "Administrator" ],
1215
// Otherwise, you can create an array of ApiKeys:
1316
"ApiKeys": [
1417
{
1518
"Value": "ArAilHVOoL3upX78Cohq",
16-
"UserName": "alice"
19+
"UserName": "alice",
20+
"Roles": [ "Administrator", "User" ]
1721
},
1822
{
1923
"Value": "DiUU5EqImTYkxPDAxBVS",
20-
"UserName": "bob"
24+
"UserName": "bob",
25+
"Roles": [ "User" ]
2126
}
2227
]
2328
// You can also combine both declarations.

samples/Controllers/BasicAuthenticationSample/Controllers/MeController.cs

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
using System.Net.Mime;
22
using Microsoft.AspNetCore.Authorization;
33
using Microsoft.AspNetCore.Mvc;
4+
using Microsoft.Extensions.Options;
5+
using SimpleAuthentication.BasicAuthentication;
46

57
namespace BasicAuthenticationSample.Controllers;
68

@@ -13,8 +15,27 @@ public class MeController : ControllerBase
1315
[HttpGet]
1416
[ProducesResponseType<User>(StatusCodes.Status200OK)]
1517
[ProducesDefaultResponseType]
16-
public ActionResult<User> Get()
17-
=> new User(User.Identity!.Name);
18+
public ActionResult<User> Get(IOptions<BasicAuthenticationSettings> basicAuthenticationSettingsOptions)
19+
{
20+
// Get roles using the configured role claim type from options (default is ClaimTypes.Role)
21+
var roles = User.FindAll(basicAuthenticationSettingsOptions.Value.RoleClaimType).Select(c => c.Value);
22+
23+
return new User(User.Identity!.Name, roles);
24+
}
25+
26+
[Authorize(Roles = "Administrator")]
27+
[HttpGet("administrator")]
28+
[ProducesResponseType(StatusCodes.Status204NoContent)]
29+
[EndpointDescription("This endpoint requires the user to have the 'Administrator' role")]
30+
public IActionResult AdministratorOnly()
31+
=> NoContent();
32+
33+
[Authorize(Roles = "User")]
34+
[HttpGet("user")]
35+
[ProducesResponseType(StatusCodes.Status204NoContent)]
36+
[EndpointDescription("This endpoint requires the user to have the 'User' role")]
37+
public IActionResult UserOnly()
38+
=> NoContent();
1839
}
1940

20-
public record class User(string? UserName);
41+
public record class User(string? UserName, IEnumerable<string> Roles);

samples/Controllers/BasicAuthenticationSample/appsettings.json

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,18 @@
88
//"RoleClaimType": "user_role", // Default: http://schemas.microsoft.com/ws/2008/06/identity/claims/role
99
"UserName": "marco",
1010
"Password": "P@$$w0rd",
11+
"Roles": [ "Administrator" ],
1112
// Otherwise, you can create an array of Credentials:
1213
"Credentials": [
1314
{
1415
"UserName": "alice",
15-
"Password": "Password1"
16+
"Password": "Password1",
17+
"Roles": [ "Administrator", "User" ]
1618
},
1719
{
1820
"UserName": "bob",
19-
"Password": "Password2"
21+
"Password": "Password2",
22+
"Roles": [ "User" ]
2023
}
2124
]
2225
// You can also combine both declarations.

samples/MinimalApis/ApiKeySample/Program.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,11 +65,11 @@
6565
.RequireAuthorization();
6666

6767
app.MapGet("api/administrator", () => TypedResults.NoContent())
68-
.WithDescription("This endpoint requires the user to have the 'Administrator' role.")
68+
.WithDescription("This endpoint requires the user to have the 'Administrator' role")
6969
.RequireAuthorization(policy => policy.RequireRole("Administrator"));
7070

7171
app.MapGet("api/user", () => TypedResults.NoContent())
72-
.WithDescription("This endpoint requires the user to have the 'User' role.")
72+
.WithDescription("This endpoint requires the user to have the 'User' role")
7373
.RequireAuthorization(policy => policy.RequireRole("User"));
7474

7575
app.Run();

samples/MinimalApis/BasicAuthenticationSample/Program.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,11 +65,11 @@
6565
.RequireAuthorization();
6666

6767
app.MapGet("api/administrator", () => TypedResults.NoContent())
68-
.WithDescription("This endpoint requires the user to have the 'Administrator' role.")
68+
.WithDescription("This endpoint requires the user to have the 'Administrator' role")
6969
.RequireAuthorization(policy => policy.RequireRole("Administrator"));
7070

7171
app.MapGet("api/user", () => TypedResults.NoContent())
72-
.WithDescription("This endpoint requires the user to have the 'User' role.")
72+
.WithDescription("This endpoint requires the user to have the 'User' role")
7373
.RequireAuthorization(policy => policy.RequireRole("User"));
7474

7575
app.Run();

src/SimpleAuthentication.Abstractions/version.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"$schema": "https://raw.githubusercontent.com/dotnet/Nerdbank.GitVersioning/master/src/NerdBank.GitVersioning/version.schema.json",
3-
"version": "3.0",
3+
"version": "3.1",
44
"publicReleaseRefSpec": [
55
"^refs/heads/master$" // we release out of master
66
],

src/SimpleAuthentication.Swashbuckle/version.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"$schema": "https://raw.githubusercontent.com/dotnet/Nerdbank.GitVersioning/master/src/NerdBank.GitVersioning/version.schema.json",
3-
"version": "3.0",
3+
"version": "3.1",
44
"publicReleaseRefSpec": [
55
"^refs/heads/master$" // we release out of master
66
],

src/SimpleAuthentication/version.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"$schema": "https://raw.githubusercontent.com/dotnet/Nerdbank.GitVersioning/master/src/NerdBank.GitVersioning/version.schema.json",
3-
"version": "3.0",
3+
"version": "3.1",
44
"publicReleaseRefSpec": [
55
"^refs/heads/master$" // we release out of master
66
],

0 commit comments

Comments
 (0)