UserController.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  1. using System;
  2. using System.Linq;
  3. using System.Security.Claims;
  4. using BasicTestApp.AuthTest;
  5. using Microsoft.AspNetCore.Mvc;
  6. namespace Components.TestServer.Controllers
  7. {
  8. [Route("api/[controller]")]
  9. public class UserController : Controller
  10. {
  11. // Servers are not expected to expose everything from the server-side ClaimsPrincipal
  12. // to the client. It's up to the developer to choose what kind of authentication state
  13. // data is needed on the client so it can display suitable options in the UI.
  14. // In this class, we inform the client only about certain roles and certain other claims.
  15. static string[] ExposedRoles = new[] { "IrrelevantRole", "TestRole" };
  16. // GET api/user
  17. [HttpGet]
  18. public ClientSideAuthenticationStateData Get()
  19. {
  20. return new ClientSideAuthenticationStateData
  21. {
  22. IsAuthenticated = User.Identity.IsAuthenticated,
  23. UserName = User.Identity.Name,
  24. ExposedClaims = User.Claims
  25. .Where(c => c.Type == "test-claim" || IsExposedRole(c))
  26. .Select(c => (c.Type, c.Value)).ToList()
  27. };
  28. }
  29. private bool IsExposedRole(Claim claim)
  30. => claim.Type == ClaimTypes.Role
  31. && ExposedRoles.Contains(claim.Value);
  32. }
  33. }