Exemple #1
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"))
            {
                // We are just looking for signalr clients
                return(Task.CompletedTask);
            }

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

            if (qsAuthToken == null)
            {
                // Cookie value does not matches to querystring value
                return(Task.CompletedTask);
            }

            // Set auth token from cookie
            context.Token = SimpleStringCipher.Instance.Decrypt(qsAuthToken, AppConsts.DefaultPassPhrase);
            return(Task.CompletedTask);
        }
        /* 此方法用于授权SignalR javascript客户端。
         * SignalR无法发送授权头。我们从查询字符串中获取加密文本。 */
        private static Task QueryStringTokenResolver(MessageReceivedContext context)
        {
            if (!context.HttpContext.Request.Path.HasValue ||
                !context.HttpContext.Request.Path.Value.StartsWith("/signalr"))
            {
                // 我们只是在寻找signalr客户
                return(Task.CompletedTask);
            }

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

            if (qsAuthToken == null)
            {
                // Cookie值与querystring值不匹配
                return(Task.CompletedTask);
            }

            // 从cookie设置身份令牌
            context.Token = SimpleStringCipher.Instance.Decrypt(qsAuthToken, AppConsts.DefaultPassPhrase);
            return(Task.CompletedTask);
        }
Exemple #3
0
 /// <summary>
 /// 用于从QueryString以及cookie中读取token
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 private static Task TokenResolver(MessageReceivedContext context)
 {
     try
     {
         if (context.Request.Query.ContainsKey("token"))
         {
             //解密后才是真正的token
             context.Token = SimpleStringCipher.Instance.Decrypt(context.Request.Query["token"], AppConsts.DefaultPassPhrase);
             //query中有token的,直接写入到cookies中
             context.Response.Cookies.Append("token", context.Request.Query["token"]);
         }
         if (context.Request.Cookies.ContainsKey("token"))
         {
             //解密后才是真正的token
             context.Token = SimpleStringCipher.Instance.Decrypt(context.Request.Cookies["token"], AppConsts.DefaultPassPhrase);
         }
     }
     catch
     {
     }
     return(Task.CompletedTask);
 }
Exemple #4
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", StringComparison.InvariantCulture))
            {
                // We are just looking for signalr clients
                return(Task.CompletedTask);
            }

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

            if (qsAuthToken == null || qsAuthToken == "null")
            {
                // Cookie value does not matches to querystring value
                return(Task.CompletedTask);
            }

            // Set auth token from cookie
            // TODO: Commented by Bishoy to be replaced by the new IdentityServer token authorization
            // context.Token = SimpleStringCipher.Instance.Decrypt(qsAuthToken, AppConsts.DefaultPassPhrase);
            return(Task.CompletedTask);
        }
        public async Task Execute(MessageReceivedContext <T> context, Next <MessageReceivedContext <T> > next)
        {
            var rbc        = (RabbitMqMessageReceivedContext <T>)context;
            var properties = rbc.Payload.BasicProperties;
            var headers    = properties?.Headers?.ToDictionary(key => key.Key, pair => pair.Value.ToString())
                             ?? new Dictionary <string, string>();

            var content      = Encoding.UTF8.GetString(rbc.Payload.Body.ToArray());
            var deserialized = _serializer.Deserialize <T>(content);

            var msg = new Message <T>()
            {
                Metadata      = headers,
                Body          = deserialized,
                CorrelationId = properties.CorrelationId,
                Id            = properties.MessageId,
                DateTime      = ConvertFromUnixTimestamp(properties.Timestamp.UnixTime)
            };

            context.Message = msg;
            await next(context);
        }
    public async Task ResolveAuthorityAndKeysAsync_SetsUpAuthorityAndKeysOnTheTokenValidationParametersAsync()
    {
        // Arrange
        var localApiDescriptor = new Mock <IIdentityServerJwtDescriptor>();

        localApiDescriptor.Setup(lad => lad.GetResourceDefinitions())
        .Returns(new Dictionary <string, ResourceDefinition>
        {
            ["TestAPI"] = new ResourceDefinition {
                Profile = ApplicationProfiles.IdentityServerJwt
            }
        });

        var credentialsStore = new Mock <ISigningCredentialStore>();
        var key = new RsaSecurityKey(RSA.Create());

        credentialsStore.Setup(cs => cs.GetSigningCredentialsAsync())
        .ReturnsAsync(new SigningCredentials(key, "RS256"));

        var context = new DefaultHttpContext();

        context.Request.Scheme  = "https";
        context.Request.Host    = new HostString("localhost");
        context.RequestServices = new ServiceCollection()
                                  .AddSingleton(new IdentityServerOptions())
                                  .AddSingleton(credentialsStore.Object)
                                  .BuildServiceProvider();

        var options = new JwtBearerOptions();
        var args    = new MessageReceivedContext(context, new AuthenticationScheme("TestAPI", null, Mock.Of <IAuthenticationHandler>().GetType()), options);

        // Act
        await IdentityServerJwtBearerOptionsConfiguration.ResolveAuthorityAndKeysAsync(args);

        // Assert
        Assert.Equal("https://localhost", options.TokenValidationParameters.ValidIssuer);
        Assert.Equal(key, options.TokenValidationParameters.IssuerSigningKey);
    }
Exemple #7
0
        public override Task MessageReceived(MessageReceivedContext context)
        {
            if (context.Request.Path.Value.StartsWith("/hubs") &&
                context.Token == null &&
                (context.Request.Headers.TryGetValue("Authorization", out StringValues token) ||
                 context.Request.Query.TryGetValue("access_token", out StringValues token2)))
            {
                // pull token from header or querystring; websockets don't support headers so fallback to query is required
                var          tokenValue = token.FirstOrDefault() ?? token2.FirstOrDefault();
                const string prefix     = "Bearer ";
                // remove prefix of header value
                if (tokenValue?.StartsWith(prefix) ?? false)
                {
                    context.Token = tokenValue.Substring(prefix.Length);
                }
                else
                {
                    context.Token = tokenValue;
                }
            }

            return(Task.CompletedTask);
        }
Exemple #8
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)
            {
                return(Task.CompletedTask);
            }

            if (context.HttpContext.Request.Path.Value.StartsWith("/signalr"))
            {
                var env    = context.HttpContext.RequestServices.GetService <IHostingEnvironment>();
                var config = env.GetAppConfiguration();
                var allowAnonymousSignalRConnection = bool.Parse(config["App:AllowAnonymousSignalRConnection"]);

                return(SetToken(context, allowAnonymousSignalRConnection));
            }

            if (context.HttpContext.Request.Path.Value.Contains("/Chat/GetUploadedObject"))
            {
                return(SetToken(context, false));
            }

            return(Task.CompletedTask);
        }
Exemple #9
0
        public static Task OnMessageReceived(MessageReceivedContext context)
        {
            string scheme = context.Scheme.Name;
            string token  = string.Empty;
            // get the scheme from the header
            string header = (string)context.Request.Headers["Authorization"];

            if (string.IsNullOrEmpty(header))
            {
                var queryAuth = context.Request.Query["Authorization"];

                if (queryAuth.Count > 0)
                {
                    header = queryAuth[0];
                }
            }

            if (string.IsNullOrEmpty(header))
            {
                context.Fail(new ApplicationException("No header present"));
                return(Task.FromResult(true));
            }
            if (header.StartsWith($"{scheme} ", StringComparison.OrdinalIgnoreCase))
            {
                token = header.Substring($"{scheme} ".Length).Trim();
            }
            if (string.IsNullOrEmpty(token))
            {
                return(Task.FromResult(true));
            }

            // we got a token for the scheme, update so the rest of the request will process it
            // Update so the middleware can process
            context.Request.Headers["Authorization"] = $"Bearer {token}";

            return(Task.FromResult(true));
        }
Exemple #10
0
 internal static Task MessageReceived(MessageReceivedContext context)
 {
     Helpers.ThrowIfConditionFailed(() => context.ProtocolMessage != null, "ProtocolMessage is null.");
     eventsFired.Add(nameof(MessageReceived));
     return(Task.FromResult(0));
 }
Exemple #11
0
 public Task MessageReceived(MessageReceivedContext context)
 {
     return(Task.FromResult(0));
 }
 // Including these as placeholders for convenient future use
 private Task OnMessageReceivedFunc(MessageReceivedContext arg)
 {
     return(Task.CompletedTask);
 }
Exemple #13
0
        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;
        }
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            try
            {
                var messageReceivedContext = new MessageReceivedContext(this.Context, this.Scheme, this.Options);

                await this.Events.MessageReceived(messageReceivedContext);

                string apiKey = messageReceivedContext.ApiKey;

                if (string.IsNullOrEmpty(apiKey))
                {
                    string header = this.Request.Headers[this.Options.Header];

                    if (string.IsNullOrEmpty(header))
                    {
                        this.Logger.ApiKeyValidationFailed();

                        return(AuthenticateResult.NoResult());
                    }

                    if (header.StartsWith(this.Options.HeaderKey, StringComparison.OrdinalIgnoreCase))
                    {
                        apiKey = header.Substring(this.Options.HeaderKey.Length).Trim();

                        var validateApiKeyContext = new ApiKeyValidatedContext(this.Context, this.Scheme, this.Options)
                        {
                            ApiKey    = apiKey,
                            Principal = new ClaimsPrincipal()
                        };

                        await this.Events.ApiKeyValidated(validateApiKeyContext);

                        if (validateApiKeyContext.Result != null)
                        {
                            this.Logger.ApiKeyValidationSucceeded();

                            return(validateApiKeyContext.Result);
                        }
                    }
                }

                this.Logger.ApiKeyValidationFailed();

                return(AuthenticateResult.NoResult());
            }
            catch (Exception ex)
            {
                this.Logger.ErrorProcessingMessage(ex);

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

                await this.Events.AuthenticationFailed(authenticationFailedContext);

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

                throw;
            }
        }
Exemple #15
0
    /// <summary>
    /// Invoked to process incoming authentication messages.
    /// </summary>
    /// <returns></returns>
    protected override async Task <HandleRequestResult> HandleRemoteAuthenticateAsync()
    {
        WsFederationMessage?     wsFederationMessage = null;
        AuthenticationProperties?properties          = null;

        // assumption: if the ContentType is "application/x-www-form-urlencoded" it should be safe to read as it is small.
        if (HttpMethods.IsPost(Request.Method) &&
            !string.IsNullOrEmpty(Request.ContentType)
            // May have media/type; charset=utf-8, allow partial match.
            && Request.ContentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase) &&
            Request.Body.CanRead)
        {
            var form = await Request.ReadFormAsync(Context.RequestAborted);

            // ToArray handles the StringValues.IsNullOrEmpty case. We assume non-empty Value does not contain null elements.
#pragma warning disable CS8620 // Argument cannot be used for parameter due to differences in the nullability of reference types.
            wsFederationMessage = new WsFederationMessage(form.Select(pair => new KeyValuePair <string, string[]>(pair.Key, pair.Value.ToArray())));
#pragma warning restore CS8620 // Argument cannot be used for parameter due to differences in the nullability of reference types.
        }

        if (wsFederationMessage == null || !wsFederationMessage.IsSignInMessage)
        {
            if (Options.SkipUnrecognizedRequests)
            {
                // Not for us?
                return(HandleRequestResult.SkipHandler());
            }

            return(HandleRequestResult.Fail("No message."));
        }

        try
        {
            // Retrieve our cached redirect uri
            var state = wsFederationMessage.Wctx;
            // WsFed allows for uninitiated logins, state may be missing. See AllowUnsolicitedLogins.
            properties = Options.StateDataFormat.Unprotect(state);

            if (properties == null)
            {
                if (!Options.AllowUnsolicitedLogins)
                {
                    return(HandleRequestResult.Fail("Unsolicited logins are not allowed."));
                }
            }
            else
            {
                // Extract the user state from properties and reset.
                properties.Items.TryGetValue(WsFederationDefaults.UserstatePropertiesKey, out var userState);
                wsFederationMessage.Wctx = userState;
            }

            var messageReceivedContext = new MessageReceivedContext(Context, Scheme, Options, properties)
            {
                ProtocolMessage = wsFederationMessage
            };
            await Events.MessageReceived(messageReceivedContext);

            if (messageReceivedContext.Result != null)
            {
                return(messageReceivedContext.Result);
            }
            wsFederationMessage = messageReceivedContext.ProtocolMessage;
            properties          = messageReceivedContext.Properties !; // Provides a new instance if not set.

            // If state did flow from the challenge then validate it. See AllowUnsolicitedLogins above.
            if (properties.Items.TryGetValue(CorrelationProperty, out string?correlationId) &&
                !ValidateCorrelationId(properties))
            {
                return(HandleRequestResult.Fail("Correlation failed.", properties));
            }

            if (wsFederationMessage.Wresult == null)
            {
                Logger.SignInWithoutWResult();
                return(HandleRequestResult.Fail(Resources.SignInMessageWresultIsMissing, properties));
            }

            var token = wsFederationMessage.GetToken();
            if (string.IsNullOrEmpty(token))
            {
                Logger.SignInWithoutToken();
                return(HandleRequestResult.Fail(Resources.SignInMessageTokenIsMissing, properties));
            }

            var securityTokenReceivedContext = new SecurityTokenReceivedContext(Context, Scheme, Options, properties)
            {
                ProtocolMessage = wsFederationMessage
            };
            await Events.SecurityTokenReceived(securityTokenReceivedContext);

            if (securityTokenReceivedContext.Result != null)
            {
                return(securityTokenReceivedContext.Result);
            }
            wsFederationMessage = securityTokenReceivedContext.ProtocolMessage;
            properties          = messageReceivedContext.Properties !;

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

            // Copy and augment to avoid cross request race conditions for updated configurations.
            var tvp     = Options.TokenValidationParameters.Clone();
            var issuers = new[] { _configuration.Issuer };
            tvp.ValidIssuers      = (tvp.ValidIssuers == null ? issuers : tvp.ValidIssuers.Concat(issuers));
            tvp.IssuerSigningKeys = (tvp.IssuerSigningKeys == null ? _configuration.SigningKeys : tvp.IssuerSigningKeys.Concat(_configuration.SigningKeys));

            ClaimsPrincipal?principal   = null;
            SecurityToken?  parsedToken = null;
            foreach (var validator in Options.SecurityTokenHandlers)
            {
                if (validator.CanReadToken(token))
                {
                    principal = validator.ValidateToken(token, tvp, out parsedToken);
                    break;
                }
            }

            if (principal == null)
            {
                throw new SecurityTokenException(Resources.Exception_NoTokenValidatorFound);
            }

            if (Options.UseTokenLifetime && parsedToken != null)
            {
                // Override any session persistence to match the token lifetime.
                var issued = parsedToken.ValidFrom;
                if (issued != DateTime.MinValue)
                {
                    properties.IssuedUtc = issued.ToUniversalTime();
                }
                var expires = parsedToken.ValidTo;
                if (expires != DateTime.MinValue)
                {
                    properties.ExpiresUtc = expires.ToUniversalTime();
                }
                properties.AllowRefresh = false;
            }

            var securityTokenValidatedContext = new SecurityTokenValidatedContext(Context, Scheme, Options, principal, properties)
            {
                ProtocolMessage = wsFederationMessage,
                SecurityToken   = parsedToken,
            };

            await Events.SecurityTokenValidated(securityTokenValidatedContext);

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

            // Flow possible changes
            principal  = securityTokenValidatedContext.Principal !;
            properties = securityTokenValidatedContext.Properties;

            return(HandleRequestResult.Success(new AuthenticationTicket(principal, properties, Scheme.Name)));
        }
        catch (Exception exception)
        {
            Logger.ExceptionProcessingMessage(exception);

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

            var authenticationFailedContext = new AuthenticationFailedContext(Context, Scheme, Options)
            {
                ProtocolMessage = wsFederationMessage,
                Exception       = exception
            };
            await Events.AuthenticationFailed(authenticationFailedContext);

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

            return(HandleRequestResult.Fail(exception, properties));
        }
    }
 private static Task context(MessageReceivedContext arg)
 {
     throw new NotImplementedException();
 }
        public async Task AddMessage(string message, MessageReceivedContext receivedContext)
        {
            var asd = receivedContext.Request.Headers["Accept"];

            await Clients.All.SendAsync("SendAction", message);
        }
 public async Task AddMessage1(string message, MessageReceivedContext receivedContext)
 {
     var asd = Context;
     await Clients.All.SendAsync("SendAction", message);
 }
Exemple #19
0
 public override Task MessageReceived(MessageReceivedContext context)
 {
     GetLogger(context).LogCallerMethodName();
     return(base.MessageReceived(context));
 }
 /// <summary>
 ///  用于获取授权tokey不在头信息的请求,目前主要考虑signalr
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 private static Task QueryStringTokenResolver(MessageReceivedContext context)
 {
     return(Task.CompletedTask);
 }
Exemple #21
0
 public override Task MessageReceived(MessageReceivedContext context)
 {
     return(base.MessageReceived(context));
 }
Exemple #22
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[HeaderNames.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());
                    }
                }

                var currentConfiguration = await this.dynamicJwtBearerHanderConfigurationResolver.ResolveCurrentOpenIdConfiguration(Context);

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

                    validationParameters.IssuerSigningKeys = validationParameters.IssuerSigningKeys?.Concat(currentConfiguration.SigningKeys)
                                                             ?? currentConfiguration.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(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;
            }
        }
Exemple #23
0
 /// <summary>
 /// Invoked when a protocol message is first received.
 /// </summary>
 public virtual Task MessageReceived(MessageReceivedContext context) => OnMessageReceived(context);
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            AuthenticateResult result = default(AuthenticateResult);

            try
            {
                MessageReceivedContext messageReceivedContext = new MessageReceivedContext(base.Context, base.Scheme, base.Options);
                await Events.MessageReceived(messageReceivedContext);

                if (messageReceivedContext.Result != null)
                {
                    result = messageReceivedContext.Result;
                    return(result);
                }
                string token = messageReceivedContext.Token;
                if (string.IsNullOrEmpty(token))
                {
                    string text = base.Request.Headers[HeaderNames.Authorization];
                    if (string.IsNullOrEmpty(text))
                    {
                        result = AuthenticateResult.NoResult();
                        return(result);
                    }
                    if (text.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
                    {
                        token = text.Substring("Bearer ".Length).Trim();
                    }
                    if (string.IsNullOrEmpty(token))
                    {
                        result = AuthenticateResult.NoResult();
                        return(result);
                    }
                }
                if (_configuration == null && base.Options.ConfigurationManager != null)
                {
                    _configuration = await base.Options.ConfigurationManager.GetConfigurationAsync(base.Context.RequestAborted);
                }
                TokenValidationParameters tokenValidationParameters = base.Options.TokenValidationParameters.Clone();
                if (_configuration != null)
                {
                    string[] array = new string[1]
                    {
                        _configuration.Issuer
                    };
                    tokenValidationParameters.ValidIssuers      = (tokenValidationParameters.ValidIssuers?.Concat(array) ?? array);
                    tokenValidationParameters.IssuerSigningKeys = (tokenValidationParameters.IssuerSigningKeys?.Concat(_configuration.SigningKeys) ?? _configuration.SigningKeys);
                }
                List <Exception> list = null;
                foreach (ISecurityTokenValidator securityTokenValidator in base.Options.SecurityTokenValidators)
                {
                    if (!securityTokenValidator.CanReadToken(token))
                    {
                        continue;
                    }
                    ClaimsPrincipal principal;
                    SecurityToken   validatedToken;
                    try
                    {
                        principal = securityTokenValidator.ValidateToken(token, tokenValidationParameters, out validatedToken);
                    }
                    catch (Exception ex)
                    {
                        Logger.TokenValidationFailed(ex);
                        if (base.Options.RefreshOnIssuerKeyNotFound && base.Options.ConfigurationManager != null && ex is SecurityTokenSignatureKeyNotFoundException)
                        {
                            base.Options.ConfigurationManager.RequestRefresh();
                        }
                        if (list == null)
                        {
                            list = new List <Exception>(1);
                        }
                        list.Add(ex);
                        continue;
                    }
                    base.Logger.TokenValidationSucceeded();
                    TokenValidatedContext tokenValidatedContext = new TokenValidatedContext(base.Context, base.Scheme, base.Options)
                    {
                        Principal     = principal,
                        SecurityToken = validatedToken
                    };
                    await Events.TokenValidated(tokenValidatedContext);

                    if (tokenValidatedContext.Result != null)
                    {
                        result = tokenValidatedContext.Result;
                        return(result);
                    }
                    if (base.Options.SaveToken)
                    {
                        tokenValidatedContext.Properties.StoreTokens(new AuthenticationToken[1]
                        {
                            new AuthenticationToken
                            {
                                Name  = "access_token",
                                Value = token
                            }
                        });
                    }
                    tokenValidatedContext.Success();
                    result = tokenValidatedContext.Result;
                    return(result);
                }
                if (list != null)
                {
                    AuthenticationFailedContext authenticationFailedContext2 = new AuthenticationFailedContext(base.Context, base.Scheme, base.Options)
                    {
                        Exception = ((list.Count == 1) ? list[0] : new AggregateException(list))
                    };
                    await Events.AuthenticationFailed(authenticationFailedContext2);

                    if (authenticationFailedContext2.Result != null)
                    {
                        result = authenticationFailedContext2.Result;
                        return(result);
                    }
                    result = AuthenticateResult.Fail(authenticationFailedContext2.Exception);
                    return(result);
                }
                result = AuthenticateResult.Fail("No SecurityTokenValidator available for token: " + token);
                return(result);
            }
            catch (Exception ex2)
            {
                Exception ex3 = ex2;
                base.Logger.ErrorProcessingMessage(ex3);
                AuthenticationFailedContext authenticationFailedContext2 = new AuthenticationFailedContext(base.Context, base.Scheme, base.Options)
                {
                    Exception = ex3
                };
                await Events.AuthenticationFailed(authenticationFailedContext2);

                if (authenticationFailedContext2.Result != null)
                {
                    return(authenticationFailedContext2.Result);
                }
                ExceptionDispatchInfo.Capture((ex2 as Exception) ?? throw ex2).Throw();
            }
            return(result);
        }
 private static Task OnMessageReceived(MessageReceivedContext context)
 {
     return(Task.FromResult(0));
 }
Exemple #26
0
 public override Task MessageReceived(MessageReceivedContext context)
 {
     GetTokensFromRequestContext(context.HttpContext.Request, out string accessToken, out string refreshToken);
     context.Token = accessToken;
     return(Task.CompletedTask);
 }
 public static Task OnAccessTokenMessageReceived(MessageReceivedContext context)
 {
     return(Task.CompletedTask);
 }
Exemple #28
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("FakeBearer ", StringComparison.OrdinalIgnoreCase))
                    {
                        token = authorization.Substring("FakeBearer ".Length).Trim();
                    }

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

                dynamic tokenDecoded = JsonConvert.DeserializeObject <Dictionary <string, dynamic> >(token);

                ClaimsIdentity id = new ClaimsIdentity("Identity.Application", "name", "role");

                foreach (var td in tokenDecoded)
                {
                    if (td.Key == "sub")
                    {
                        id.AddClaim(new Claim("sub", td.Value.ToString()));
                        id.AddClaim(new Claim("name", td.Value.ToString()));
                    }
                    else
                    {
                        if (td.Value is string)
                        {
                            id.AddClaim(new Claim(td.Key, td.Value));
                        }
                        else if (td.Value is IEnumerable)
                        {
                            foreach (string subValue in td.Value)
                            {
                                id.AddClaim(new Claim(td.Key, subValue));
                            }
                        }
                        else
                        {
                            throw new Exception("Unknown type");
                        }
                    }
                }

                ClaimsPrincipal principal = new ClaimsPrincipal(id);

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

                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);
            }
            catch (Exception ex)
            {
                var authenticationFailedContext = new AuthenticationFailedContext(Context, Scheme, Options)
                {
                    Exception = ex
                };

                await Events.AuthenticationFailed(authenticationFailedContext);

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

                throw;
            }
        }
Exemple #29
0
 /// <summary>
 /// Messages the received.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <returns>Task.</returns>
 public override async Task MessageReceived(MessageReceivedContext context)
 {
     await base.MessageReceived(context);
 }
        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);
            }
        }