Protected Resource Builder MVC
This article demonstrates how to add Protected Resource Builder to an MVC project. Here is how to add resource authorization:
TIP
💡See Resource Authorization Reference Solution to see a real world example of how to use Protected Resource Builder.
Register Protected Resource Builder for MVC
csharp
services.AddControllers(options => options.AddProtectedResources());
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddKeycloakWebApi(context.Configuration);
services
.AddAuthorization()
.AddKeycloakAuthorization()
.AddAuthorizationServer(context.Configuration);
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
Apply ProtectedResourceAttribute
cs
[ApiController]
[Route("workspaces")]
[ProtectedResource("workspaces")]
public class WorkspacesController : ControllerBase
{
[HttpGet]
[ProtectedResource("workspaces", "workspace:list")]
public ActionResult<IEnumerable<string>> GetWorkspacesAsync() => this.Ok(Array.Empty<string>());
[HttpGet("public")]
[IgnoreProtectedResource]
public IActionResult GetPublicWorkspaceAsync() => this.Ok(new { Id = "public" });
[HttpGet("{id}")]
[ProtectedResource("{id}", "workspace:read")]
public IActionResult GetWorkspaceAsync(string id) => this.Ok(new { id });
[HttpDelete("{id}")]
[ProtectedResource("{id}", "workspace:delete")]
public IActionResult DeleteWorkspaceAsync(string id) =>
string.IsNullOrWhiteSpace(id) ? this.BadRequest() : this.NoContent();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22