Esempio n. 1
0
            // MessageReceived event
            private Task MessageReceived(Microsoft.AspNetCore.Authentication.JwtBearer.MessageReceivedContext context)
            {
                // If no token found, no further work possible
                if (string.IsNullOrEmpty(context.Token))
                {
                    //return AuthenticateResult.NoResult();
                }

                return(Task.FromResult(0));
            }
Esempio n. 2
0
        /* This method is needed to authorize SignalR javascript client.
         * SignalR can not send authorization header. So, we are getting it from query string as an encrypted text. */
        private static Task QueryStringTokenResolver(MessageReceivedContext context)
        {
            if (!context.HttpContext.Request.Path.HasValue ||
                !context.HttpContext.Request.Path.Value.StartsWith("/signalr"))
            {
                return(Task.CompletedTask);
            }

            var qsAuthToken = context.HttpContext.Request.Query["enc_auth_token"].FirstOrDefault();

            if (qsAuthToken == null)
            {
                return(Task.CompletedTask);
            }

            // Set auth token from cookie
            context.Token = SimpleStringCipher.Instance.Decrypt(qsAuthToken, AppConsts.DefaultPassPhrase);
            return(Task.CompletedTask);
        }
Esempio n. 3
0
        /// <summary>
        /// Searches the 'Authorization' header for a 'Bearer' token. If the 'Bearer' token is found, it is validated using <see cref="TokenValidationParameters"/> set in the options.
        /// </summary>
        /// <returns></returns>
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            string token = null;

            try
            {
                // Give application opportunity to find from a different location, adjust, or reject token
                var messageReceivedContext = new MessageReceivedContext(Context, Scheme, Options);

                // event can set the token
                await Events.MessageReceived(messageReceivedContext);

                if (messageReceivedContext.Result != null)
                {
                    return(messageReceivedContext.Result);
                }

                // If application retrieved token from somewhere else, use that.
                token = messageReceivedContext.Token;

                if (string.IsNullOrEmpty(token))
                {
                    string authorization = Request.Headers["Authorization"];

                    // If no authorization header found, nothing to process further
                    if (string.IsNullOrEmpty(authorization))
                    {
                        return(AuthenticateResult.NoResult());
                    }

                    if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
                    {
                        token = authorization.Substring("Bearer ".Length).Trim();
                    }

                    // If no token found, no further work possible
                    if (string.IsNullOrEmpty(token))
                    {
                        return(AuthenticateResult.NoResult());
                    }
                }

                if (_configuration == null && Options.ConfigurationManager != null)
                {
                    _configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.RequestAborted);
                }

                var validationParameters = Options.TokenValidationParameters.Clone();
                if (_configuration != null)
                {
                    var issuers = new[] { _configuration.Issuer };
                    validationParameters.ValidIssuers = validationParameters.ValidIssuers?.Concat(issuers) ?? issuers;

                    validationParameters.IssuerSigningKeys = validationParameters.IssuerSigningKeys?.Concat(_configuration.SigningKeys)
                                                             ?? _configuration.SigningKeys;
                }

                List <Exception> validationFailures = null;
                SecurityToken    validatedToken;
                foreach (var validator in Options.SecurityTokenValidators)
                {
                    if (validator.CanReadToken(token))
                    {
                        ClaimsPrincipal principal;
                        try
                        {
                            principal = validator.ValidateToken(token, validationParameters, out validatedToken);
                        }
                        catch (Exception ex)
                        {
                            Logger.TokenValidationFailed(token, ex);

                            // Refresh the configuration for exceptions that may be caused by key rollovers. The user can also request a refresh in the event.
                            if (Options.RefreshOnIssuerKeyNotFound && Options.ConfigurationManager != null &&
                                ex is SecurityTokenSignatureKeyNotFoundException)
                            {
                                Options.ConfigurationManager.RequestRefresh();
                            }

                            if (validationFailures == null)
                            {
                                validationFailures = new List <Exception>(1);
                            }
                            validationFailures.Add(ex);
                            continue;
                        }

                        Logger.TokenValidationSucceeded();

                        var tokenValidatedContext = new TokenValidatedContext(Context, Scheme, Options)
                        {
                            Principal     = principal,
                            SecurityToken = validatedToken
                        };

                        await Events.TokenValidated(tokenValidatedContext);

                        if (tokenValidatedContext.Result != null)
                        {
                            return(tokenValidatedContext.Result);
                        }

                        if (Options.SaveToken)
                        {
                            tokenValidatedContext.Properties.StoreTokens(new[]
                            {
                                new AuthenticationToken {
                                    Name = "access_token", Value = token
                                }
                            });
                        }

                        tokenValidatedContext.Success();
                        return(tokenValidatedContext.Result);
                    }
                }

                if (validationFailures != null)
                {
                    var authenticationFailedContext = new AuthenticationFailedContext(Context, Scheme, Options)
                    {
                        Exception = (validationFailures.Count == 1) ? validationFailures[0] : new AggregateException(validationFailures)
                    };

                    await Events.AuthenticationFailed(authenticationFailedContext);

                    if (authenticationFailedContext.Result != null)
                    {
                        return(authenticationFailedContext.Result);
                    }

                    return(AuthenticateResult.Fail(authenticationFailedContext.Exception));
                }

                return(AuthenticateResult.Fail("No SecurityTokenValidator available for token: " + token ?? "[null]"));
            }
            catch (Exception ex)
            {
                Logger.ErrorProcessingMessage(ex);

                var authenticationFailedContext = new AuthenticationFailedContext(Context, Scheme, Options)
                {
                    Exception = ex
                };

                await Events.AuthenticationFailed(authenticationFailedContext);

                if (authenticationFailedContext.Result != null)
                {
                    return(authenticationFailedContext.Result);
                }

                throw;
            }
        }
Esempio n. 4
0
 /// <summary>
 /// Invoked when a protocol message is first received.
 /// </summary>
 public virtual Task MessageReceived(MessageReceivedContext context) => OnMessageReceived(context);
Esempio n. 5
0
 public virtual Task MessageReceived(MessageReceivedContext context) => OnMessageReceived(context);
        // private OpenIdConnectConfiguration _configuration;

        /// <summary>
        /// Searches the 'Authorization' header for a 'Bearer' token. If the 'Bearer' token is found, it is validated using <see cref="TokenValidationParameters"/> set in the options.
        /// </summary>
        /// <returns></returns>
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            string url = Microsoft.AspNetCore.Http.Extensions.UriHelper.GetDisplayUrl(Context.Request);

            System.Console.WriteLine(url);


            string             token  = null;
            AuthenticateResult result = null;

            try
            {
                // Give application opportunity to find from a different location, adjust, or reject token
                var messageReceivedContext = new MessageReceivedContext(Context, Options);

                // event can set the token
                // await Options.Events.MessageReceived(messageReceivedContext);
                if (messageReceivedContext.CheckEventResult(out result))
                {
                    return(result);
                }

                // If application retrieved token from somewhere else, use that.
                token = messageReceivedContext.Token;

                if (string.IsNullOrEmpty(token))
                {
                    string authorization = Request.Headers["Authorization"];

                    // If no authorization header found, nothing to process further
                    if (string.IsNullOrEmpty(authorization))
                    {
                        return(AuthenticateResult.Skip());
                    }

                    if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
                    {
                        token = authorization.Substring("Bearer ".Length).Trim();
                    }

                    // If no token found, no further work possible
                    if (string.IsNullOrEmpty(token))
                    {
                        return(AuthenticateResult.Skip());
                    }
                }

                /*
                 * if (_configuration == null && Options.ConfigurationManager != null)
                 * {
                 *  _configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.RequestAborted);
                 * }
                 *
                 * var validationParameters = Options.TokenValidationParameters.Clone();
                 * if (_configuration != null)
                 * {
                 *  if (validationParameters.ValidIssuer == null && !string.IsNullOrEmpty(_configuration.Issuer))
                 *  {
                 *      validationParameters.ValidIssuer = _configuration.Issuer;
                 *  }
                 *  else
                 *  {
                 *      var issuers = new[] { _configuration.Issuer };
                 *      validationParameters.ValidIssuers = (validationParameters.ValidIssuers == null ? issuers : validationParameters.ValidIssuers.Concat(issuers));
                 *  }
                 *
                 *  validationParameters.IssuerSigningKeys = (validationParameters.IssuerSigningKeys == null ? _configuration.SigningKeys : validationParameters.IssuerSigningKeys.Concat(_configuration.SigningKeys));
                 * }
                 */


                /*
                 * List<Exception> validationFailures = null;
                 * SecurityToken validatedToken;
                 * foreach (var validator in Options.SecurityTokenValidators)
                 * {
                 *  if (validator.CanReadToken(token))
                 *  {
                 *      ClaimsPrincipal principal;
                 *      try
                 *      {
                 *          principal = validator.ValidateToken(token, validationParameters, out validatedToken);
                 *      }
                 *      catch (Exception ex)
                 *      {
                 *          Logger.TokenValidationFailed(token, ex);
                 *
                 *          // Refresh the configuration for exceptions that may be caused by key rollovers. The user can also request a refresh in the event.
                 *          if (Options.RefreshOnIssuerKeyNotFound && Options.ConfigurationManager != null
                 *              && ex is SecurityTokenSignatureKeyNotFoundException)
                 *          {
                 *              Options.ConfigurationManager.RequestRefresh();
                 *          }
                 *
                 *          if (validationFailures == null)
                 *          {
                 *              validationFailures = new List<Exception>(1);
                 *          }
                 *          validationFailures.Add(ex);
                 *          continue;
                 *      }
                 *
                 *      Logger.TokenValidationSucceeded();
                 *
                 *      var ticket = new AuthenticationTicket(principal, new AuthenticationProperties(), Options.AuthenticationScheme);
                 *      var tokenValidatedContext = new TokenValidatedContext(Context, Options)
                 *      {
                 *          Ticket = ticket,
                 *          SecurityToken = validatedToken,
                 *      };
                 *
                 *      await Options.Events.TokenValidated(tokenValidatedContext);
                 *      if (tokenValidatedContext.CheckEventResult(out result))
                 *      {
                 *          return result;
                 *      }
                 *      ticket = tokenValidatedContext.Ticket;
                 *
                 *      if (Options.SaveToken)
                 *      {
                 *          ticket.Properties.StoreTokens(new[]
                 *          {
                 *              new AuthenticationToken { Name = "access_token", Value = token }
                 *          });
                 *      }
                 *
                 *      return AuthenticateResult.Success(ticket);
                 *  }
                 * }
                 */

                /*
                 * if (validationFailures != null)
                 * {
                 *  var authenticationFailedContext = new AuthenticationFailedContext(Context, Options)
                 *  {
                 *      Exception = (validationFailures.Count == 1) ? validationFailures[0] : new AggregateException(validationFailures)
                 *  };
                 *
                 *  await Options.Events.AuthenticationFailed(authenticationFailedContext);
                 *  if (authenticationFailedContext.CheckEventResult(out result))
                 *  {
                 *      return result;
                 *  }
                 *
                 *  return AuthenticateResult.Fail(authenticationFailedContext.Exception);
                 * }
                 */
                return(AuthenticateResult.Fail("No SecurityTokenValidator available for token: " + token ?? "[null]"));
            }
            catch (Exception ex)
            {
                // Logger.ErrorProcessingMessage(ex);

                var authenticationFailedContext = new AuthenticationFailedContext(Context, Options)
                {
                    Exception = ex
                };

                // await Options.Events.AuthenticationFailed(authenticationFailedContext);
                if (authenticationFailedContext.CheckEventResult(out result))
                {
                    return(result);
                }

                throw;
            }
        }
 // Replaced: https://github.com/aspnet/Security/commit/3f596108aac3d8fc7fb40d39e19a7f897a90c198
 public override Task MessageReceived(MessageReceivedContext context)
 {
     _logger.TokenReceived();
     return base.MessageReceived(context);
 }
 private Task JwtBearerMessageReceived(Microsoft.AspNetCore.Authentication.JwtBearer.MessageReceivedContext arg)
 {
     _logger.LogDebug("JwtBearerMessageReceived!");
     return(Task.FromResult(0));
 }
 private static Task OnMessageReceived(MessageReceivedContext arg) => Task.CompletedTask;
Esempio n. 10
0
 private static Task OnMessageReceived(MessageReceivedContext arg)
 {
     Console.WriteLine(arg);
     return(Task.FromResult(0));
 }