BotAuthenticationHandler.cs
1 using System.Security.Claims;
2 using System.Threading;
3 using System.Threading.Tasks;
4 
5 using Microsoft.AspNetCore.Authentication;
6 using Microsoft.AspNetCore.Http.Authentication;
7 using Microsoft.AspNetCore.Http.Features.Authentication;
8 
9 namespace Microsoft.Bot.Connector
10 {
14  public sealed class BotAuthenticationHandler : AuthenticationHandler<BotAuthenticationOptions>
15  {
16  protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
17  {
18  if (await Options.CredentialProvider.IsAuthenticationDisabledAsync())
19  {
20  var principal = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Role, "Bot") }));
21  return AuthenticateResult.Success(new AuthenticationTicket(principal, new AuthenticationProperties(), Options.AuthenticationScheme));
22  }
23 
24  string token = null;
25 
26  string authorization = Request.Headers["Authorization"];
27  token = authorization?.Substring("Bearer ".Length).Trim();
28 
29  // If no token found, no further work possible
30  // and Authentication is not disabled fail
31  if (string.IsNullOrEmpty(token))
32  {
33  return AuthenticateResult.Fail("No JwtToken is present and BotAuthentication is enabled!");
34  }
35 
36  var authenticator = new BotAuthenticator(Options.CredentialProvider, Options.OpenIdConfiguration, Options.DisableEmulatorTokens);
37  var identityToken = await authenticator.TryAuthenticateAsync(Options.AuthenticationScheme, token, CancellationToken.None);
38 
39  if (identityToken.Authenticated)
40  {
41  identityToken.Identity.AddClaim(new Claim(ClaimTypes.Role, "Bot"));
42  var principal = new ClaimsPrincipal(identityToken.Identity);
43  var ticket = new AuthenticationTicket(principal, new AuthenticationProperties(), Options.AuthenticationScheme);
44  Context.User = principal;
45 
46  if (Options.SaveToken)
47  {
48  ticket.Properties.StoreTokens(new[]
49  {
50  new AuthenticationToken { Name = "access_token", Value = token }
51  });
52  }
53 
54  return AuthenticateResult.Success(ticket);
55  }
56  else
57  {
58  return AuthenticateResult.Fail($"Failed to authenticate JwtToken {token}");
59  }
60  }
61  }
62 }
Bot authentication hanlder used by BotAuthenticationMiddleware.
override async Task< AuthenticateResult > HandleAuthenticateAsync()