Skip to content

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);

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();
}