25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

51 lines
1.8 KiB

  1. using System.Linq;
  2. using System.Security.Claims;
  3. using System.Text.Encodings.Web;
  4. using System.Threading.Tasks;
  5. using Microsoft.AspNetCore.Authentication;
  6. using Microsoft.Extensions.Logging;
  7. using Microsoft.Extensions.Options;
  8. namespace Sample.Dashboard.Auth
  9. {
  10. public class MyDashboardAuthenticationSchemeOptions : AuthenticationSchemeOptions
  11. {
  12. }
  13. public class MyDashboardAuthenticationHandler : AuthenticationHandler<MyDashboardAuthenticationSchemeOptions>
  14. {
  15. public MyDashboardAuthenticationHandler(IOptionsMonitor<MyDashboardAuthenticationSchemeOptions> options,
  16. ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
  17. {
  18. options.CurrentValue.ForwardChallenge = "";
  19. }
  20. protected override Task<AuthenticateResult> HandleAuthenticateAsync()
  21. {
  22. var testAuthHeaderPresent = Request.Headers["X-Base-Token"].Contains("xxx");
  23. var authResult = testAuthHeaderPresent ? AuthenticatedTestUser() : AuthenticateResult.NoResult();
  24. return Task.FromResult(authResult);
  25. }
  26. protected override Task HandleChallengeAsync(AuthenticationProperties properties)
  27. {
  28. Response.Headers["WWW-Authenticate"] = "MyDashboardScheme";
  29. return base.HandleChallengeAsync(properties);
  30. }
  31. private AuthenticateResult AuthenticatedTestUser()
  32. {
  33. var claims = new[] { new Claim(ClaimTypes.Name, "My Dashboard user") };
  34. var identity = new ClaimsIdentity(claims, "MyDashboardScheme");
  35. var principal = new ClaimsPrincipal(identity);
  36. var ticket = new AuthenticationTicket(principal, "MyDashboardScheme");
  37. return AuthenticateResult.Success(ticket);
  38. }
  39. }
  40. }