public Task MessageReceived(MessageReceivedContext context) { var principal = this.ValidateTokenAsync(context.HttpContext).Result; if (principal != null) { context.Principal = principal; context.Success(); } else { context.Fail(" Token Not Found"); } return(Task.CompletedTask); }
private async Task MessageReceivedAsync(MessageReceivedContext arg) { string aadInstance = Configuration["Authentication:AzureAd:ida:AADInstance"]; string issuer = string.Empty; List <SecurityKey> signingTokens = null; DateTime stsMetadataRetrievalTime = DateTime.MinValue; var authHeader = arg.HttpContext.Request.Headers["Authorization"]; if (String.IsNullOrEmpty(authHeader)) { var authenticatiuonHeader = new AuthenticationHeaderValue("Bearer", $"authentication_uri="); arg.HttpContext.Response.Headers.Add("Bearer", "some value here."); } // 7 = (Bearer + " ").Length var token = authHeader.ToString().Substring(7); try { string stsDiscoveryEndpoint = string.Format(_aadValidationEndpoint, _tenant, _policy); var configManager = new ConfigurationManager <OpenIdConnectConfiguration>(stsDiscoveryEndpoint, new OpenIdConnectConfigurationRetriever()); OpenIdConnectConfiguration config = null; config = await configManager.GetConfigurationAsync(); issuer = config.Issuer; signingTokens = config.SigningKeys.ToList(); stsMetadataRetrievalTime = DateTime.UtcNow; } catch (Exception ex) { // Log error } var tokenHandler = new JwtSecurityTokenHandler(); var validationParameters = new TokenValidationParameters { ValidAudience = _audience, ValidIssuer = issuer, IssuerSigningKeys = signingTokens }; var claimsPrincipal = tokenHandler.ValidateToken(token, validationParameters, out var validatedToken); // Check to see if Principal has a "new user" attribute. // IF TRUE THEN // Grab x-claims header if exists, add extra claim to the principal. // Call GraphAPI to extend new user claims. ((ClaimsIdentity)claimsPrincipal.Identity).AddClaim(new Claim("TenantId", "12345")); ((ClaimsIdentity)claimsPrincipal.Identity).AddClaim(new Claim("ABC-XYZ", "some-value")); Thread.CurrentPrincipal = claimsPrincipal; var ticket = new AuthenticationTicket(claimsPrincipal, arg.Scheme.Name); arg.Principal = claimsPrincipal; arg.HttpContext.User = claimsPrincipal; arg.Success(); return; }
private static async Task StuntmanOnMessageReceived( StuntmanOptions options, MessageReceivedContext context) { var authorizationBearerToken = context.HttpContext.Request.Headers["Authorization"]; if (string.IsNullOrWhiteSpace(authorizationBearerToken)) { // TODO: Skip to next middleware? return; } else { var authorizationBearerTokenParts = authorizationBearerToken.ToString().Split(' '); var accessToken = authorizationBearerTokenParts .LastOrDefault(); var claims = new List <Claim>(); StuntmanUser user = null; if (authorizationBearerTokenParts.Count() != 2 || string.IsNullOrWhiteSpace(accessToken)) { context.HttpContext.Response.StatusCode = 400; await context.HttpContext.Response.WriteAsync( "Authorization header is not in correct format."); context.Fail( "Authorization header is not in correct format."); return; } else { user = options.Users .Where(x => x.AccessToken == accessToken) .FirstOrDefault(); if (user == null) { if (!options.AllowBearerTokenPassthrough) { context.Response.StatusCode = 403; await context.HttpContext.Response.WriteAsync( $"options provided does not include the requested '{accessToken}' user."); } context.Fail( $"options provided does not include the requested '{accessToken}' user."); return; } else { claims.Add(new Claim("access_token", accessToken)); } } claims.Add(new Claim(user.NameClaimType, user.Name)); claims.AddRange(user.Claims); context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, Constants.StuntmanAuthenticationType, user.NameClaimType, user.RoleClaimType)); context.Success(); options.AfterBearerValidateIdentity?.Invoke(context); } }