protected ClientContext GetUserClientContext(Uri host)
        {
            var accessToken = Cache.Get(GetUserCacheKey(host.Authority));

            if (accessToken == null)
            {
                accessToken = CreateUserAccessToken(host);
                Cache.Insert(accessToken, GetUserCacheKey(host.Authority));
            }
            return(TokenHelper.GetClientContextWithAccessToken(host.AbsoluteUri, accessToken.Value));
        }
Example #2
0
        protected ClientContext GetUserClientContext(Uri host)
        {
            string      cacheKey    = GetUserCacheKey(host.Authority);
            AccessToken accessToken = Cache.Get(cacheKey);

            if (accessToken == null || !accessToken.IsValid())
            {
                accessToken = CreateUserAccessToken(host);
                Cache.Insert(accessToken, cacheKey);
            }
            return(TokenHelper.GetClientContextWithAccessToken(host.GetLeftPart(UriPartial.Path), accessToken.Value));
        }
        private IApplicationUserContext FetchFromStorage()
        {
            var key = _tokenCache.Get();

            if (key == null)
            {
                throw new KeyNotFoundException("user cookie key not found");
            }

            var appUser = _storage.Get <ApplicationUserContext>(key) ?? new ApplicationUserContext();

            _mapper.Map(appUser, _applicationUserContext);
            return(_applicationUserContext);
        }
        public IAuthenticationContext <TOut> Handle(TRequestDto request)
        {
            var token = _tokenCache.Get();

            if (string.IsNullOrEmpty(token))
            {
                Context.AddMessage("W3");
                Context.IsValidTokenProvided = false;
                return(Context);
            }

            var validationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = "Fiver.Security.Bearer", ValidAudience = "Fiver.Security.Bearer", IssuerSigningKey = JwtSecurityKey.Create("fiver-secret-key")
            };

            var principal = new JwtSecurityTokenHandler()
                            .ValidateToken(token, validationParameters, out var validatedToken);

            var email = principal.Claims.ToList()[0].Value;

            _applicationUserContext.Token = new TokenDto(token, validatedToken.ValidTo);
            _applicationUserContext.Email = email;

            var response = _executionPipeline.Execute <GetApplicationUserDto, ApplicationUserDto>(
                new GetApplicationUserDto(email));

            _mapper.Map(response.Result, _applicationUserContext);

            Context.IsValidTokenProvided = true;
            return(Context);
        }
Example #5
0
        public async Task InvokeAsync(HttpContext context)
        {
            MethodInfo method = Assembly.GetExecutingAssembly().GetTypes()
                                .FirstOrDefault(x => x.Name == "ApiController")
                                .GetMethods().Where(c => c.Module.Name == "PWApi.dll" &&
                                                    c.Name == context.Request.Path.Value.Replace("/api/pw/", string.Empty))
                                .FirstOrDefault();

            if (method != null)
            {
                bool isTokenNeed = notTokenMethods.IndexOf(method.Name) == -1 ? true : false;

                if (isTokenNeed)
                {
                    context.Request.Headers.TryGetValue("Authorization", out var tokenString);

                    string token = tokenString.ToString().Replace("Bearer ", string.Empty);

                    if (token == string.Empty || _tokenCache.Get(new Guid(token.ToString().Replace("Bearer ", string.Empty))) == 0)
                    {
                        context.Response.StatusCode = 403;
                        await context.Response.WriteAsync("Token is invalid");
                    }
                }
                await _next.Invoke(context);
            }

            if (context.Request.Path.Value == "/api/pw")
            {
                await context.Response.WriteAsync("The service was launched successfully");
            }
        }
Example #6
0
        public ActionResult <TransactPresentation> CreateTransaction([FromBody] TransactSave transaction)
        {
            StartInfo(ControllerContext.RouteData.Values["action"].ToString(), transaction);
            try
            {
                Guid token  = new Guid(Request.Headers["Authorization"].ToString().Replace("Bearer ", string.Empty));
                int  userId = _tokenCache.Get(token);

                if (userId == 0)
                {
                    isUnauthorized = true;
                    throw new InvalidOperationException(ConstStrings.AuthorizationError);
                }

                if (transaction.RecipientID == 0)
                {
                    transaction.RecipientID = userId;
                }
                else
                {
                    transaction.SenderID = userId;
                }

                TransactPresentation dateTransaction = _databasePW.CreateTransaction(transaction);

                _logger.Info(string.Format("End. Return: {0}",
                                           JsonConvert.SerializeObject(dateTransaction)));
                _logger.EndLogMethod();

                return(Ok(dateTransaction));
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                _logger.EndLogMethod();

                if (isUnauthorized)
                {
                    return(Unauthorized());
                }
                else
                {
                    return(BadRequest(ex.Message));
                }
            }
        }
        public async Task Invoke(HttpContext context)
        {
            if (!_hasProvider)
            {
                await _next(context);

                return;
            }

            try
            {
                TokenInfo tokenInfo;

                if (context.Request.Headers.ContainsKey("Authorization"))
                {
                    if (context.Request.Headers.TryGetValue("Authorization", out var authzValue) && authzValue.Any(value => value.Contains("Basic")))
                    {
                        // Add Telemetry.
                        using (var activity = _activitySource?.StartActivity("BasicAuthentication", ActivityKind.Producer))
                        {
                            var cacheKey = BuildKey(authzValue);

                            tokenInfo = _tokenCache?.Get <TokenInfo>(cacheKey);
                            if (null == tokenInfo || tokenInfo.ExpiresOnUtc < DateTime.UtcNow.AddMinutes(1))
                            {
                                var credential = GetCredential(authzValue);

                                if (null != credential && credential.CredentialsEntered)
                                {
                                    // Get an Access Token.
                                    tokenInfo = await _provider.GetTokenAsync(_option.Settings, credential);

                                    _tokenCache?.Put(cacheKey, tokenInfo);
                                }
                            }

                            if (null != tokenInfo)
                            {
                                // Replace the Basic Authorization by the access token in the header.
                                var authorization = new AuthenticationHeaderValue("Bearer", tokenInfo.AccessToken).ToString();
                                context.Request.Headers.Remove("Authorization");
                                context.Request.Headers.Add("Authorization", authorization);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Technical().Exception(ex).Log();
            }

            await _next(context);
        }
Example #8
0
        private void BeforeAccessNotification(TokenCacheNotificationArgs args)
        {
            Logger.Technical().From <Cache>().System($"Getting token info from the cache for identifier: {_identifier}.").Log();
            var tokenInfo = TokenCache?.Get <byte[]>(_identifier);

            if (default(byte[]) == tokenInfo)
            {
                Logger.Technical().From <Cache>().System($"Token info from the cache was received for identifier:{_identifier}.").Log();
                DeserializeAdalV3(null);
                return;
            }

            Logger.Technical().From <Cache>().System($"Deserializing the token information to generate a token from the cache for identifier: {_identifier}.").Log();
            DeserializeAdalV3(tokenInfo);
            Logger.Technical().From <Cache>().System($"Deserialized the token information for identifier: {_identifier}.").Log();
        }
        public IAuthenticationContext <ValidateTokenResponse> Handle(ValidateTokenRequest request)
        {
            var token = _tokenCache.Get();

            if (string.IsNullOrEmpty(token))
            {
                Context.AddMessage("W3");
                _applicationUserContext.Token.IsValidTokenProvided = false;
                return(Context);
            }

            var validationParameters = new TokenValidationParameters
            {
                ValidateIssuer           = true,
                ValidateAudience         = true,
                ValidateLifetime         = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer      = "Fiver.Security.Bearer",
                ValidAudience    = "Fiver.Security.Bearer",
                IssuerSigningKey = JwtSecurityKey.Create("fiver-secret-key")
            };

            System.Security.Claims.ClaimsPrincipal principal = null;
            SecurityToken validatedToken = null;

            try
            {
                principal = new JwtSecurityTokenHandler()
                            .ValidateToken(token, validationParameters, out validatedToken);
            }
            catch (SecurityTokenValidationException)
            {
                Context.AddMessage("E3", "Invalid Token");
                return(Context);
            }

            var email = principal.Claims.ToList()[0].Value;

            _applicationUserContext.Token = new TokenDto(token, validatedToken.ValidTo);
            _applicationUserContext.Email = email;
            _applicationUserContext.Token.IsValidTokenProvided = true;

            return(Context);
        }
Example #10
0
        protected override void Then()
        {
            var result = _tokenCache.Get();

            Assert.IsTrue(result.Equals("yy"));
        }
        public async Task <TokenInfo> GetTokenAsync(IKeyValueSettings settings, CredentialsResult credential)
        {
            var messages = GetContext(settings, out string clientId, out string authority, out string authenticationType, out string serviceApplicationId);

            if (String.IsNullOrWhiteSpace(credential.Upn))
            {
                messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Warning, "No Username is provided."));
            }

            if (String.IsNullOrWhiteSpace(credential.Password))
            {
                messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Warning, "No password is provided."));
            }

            messages.LogAndThrowIfNecessary(this);
            messages.Clear();

            if (null != TokenCache)
            {
                // Get a HashCode from the password so a second call with the same upn but with a wrong password will not be impersonated due to
                // the lack of password check.
                var cacheKey = BuildKey(credential, authority, serviceApplicationId);
                Logger.Technical().From <CredentialTokenCacheTokenProvider>().System($"Check if the cache contains a token for {cacheKey}.").Log();
                var tokenInfo  = TokenCache.Get <TokenInfo>(cacheKey);
                var hasChanged = false;

                if (null != tokenInfo)
                {
                    Logger.Technical().From <CredentialTokenCacheTokenProvider>().System($"Token loaded from the cache for {cacheKey}.").Log();

                    if (tokenInfo.ExpiresOnUtc < DateTime.UtcNow.AddMinutes(1))
                    {
                        Logger.Technical().From <CredentialTokenCacheTokenProvider>().System($"Token is expired for {cacheKey}.").Log();

                        // We need to refresh the token.
                        tokenInfo = await CreateBasicTokenInfoAsync(settings, credential);

                        hasChanged = true;
                    }
                }
                else
                {
                    Logger.Technical().From <CredentialTokenCacheTokenProvider>().System($"Contact the STS to create an access token for {cacheKey}.").Log();
                    tokenInfo = await CreateBasicTokenInfoAsync(settings, credential);

                    hasChanged = true;
                }

                if (hasChanged)
                {
                    try
                    {
                        Logger.Technical().From <CredentialTokenCacheTokenProvider>().System($"Save the token in the cache for {cacheKey}, will expire at {tokenInfo.ExpiresOnUtc} Utc.").Log();
                        TokenCache.Put(cacheKey, tokenInfo);
                    }
                    catch (Exception ex)
                    {
                        Logger.Technical().From <CredentialTokenCacheTokenProvider>().Exception(ex).Log();
                    }
                }

                return(tokenInfo);
            }

            // no cache, do a direct call on every calls.
            Logger.Technical().From <CredentialTokenCacheTokenProvider>().System($"No cache is defined. STS is called for every call.").Log();
            return(await CreateBasicTokenInfoAsync(settings, credential));
        }