public async Task <TokenReply> ReadOrRetrieveToken(ServiceSettings options)
        {
            TokenReply tokenReplyResult = null;
            var        cacheKey         = options.OAuthClientId + options.OAuthClientSecret + options.OAuthScope + options.OAuthTokenEndpoint;

            tokenReplyResult = _cache.Get <TokenReply>(cacheKey);

            if (tokenReplyResult == null)
            {
                tokenReplyResult = await RetrieveToken(options.OAuthClientId, options.OAuthClientSecret, options.OAuthScope, options.OAuthTokenEndpoint);

                var cacheExpiration = tokenReplyResult.expires_in - 60;
                cacheExpiration = cacheExpiration > 0 ? cacheExpiration : 0;

                Console.WriteLine($"Retrieved new OAuth access token for {options.Path} on end-point {options.OAuthTokenEndpoint}");

                if (cacheExpiration > 0)
                {
                    _cache.Set(cacheKey, tokenReplyResult, new MemoryCacheEntryOptions {
                        AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(cacheExpiration)
                    });
                }
            }

            return(tokenReplyResult);
        }
        public override Task <TokenReply> GetToken(TokenRequest request, ServerCallContext context)
        {
            TokenReply result = new TokenReply();

            result.ResultStatus = ResultStatus.Fail;

            string configuredSecret = _configuration["JWT_TOKEN_KEY"];

            if (configuredSecret.Equals(request.Secret))
            {
                var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuredSecret));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                var jwtSecurityToken = new JwtSecurityToken(
                    _configuration["JWT_VALID_ISSUER"],
                    _configuration["JWT_VALID_AUDIENCE"],
                    expires: DateTime.UtcNow.AddYears(5),
                    signingCredentials: creds
                    );
                result.Token        = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
                result.ResultStatus = ResultStatus.Success;
            }
            else
            {
                result.ErrorDetail = "Bad Request";
            }
            return(Task.FromResult(result));
        }
Ejemplo n.º 3
0
        public static string RegisterAccount(string login)
        {
            using var clientFabric = new GetClient <AuthenticatorClient>(d => new AuthenticatorClient(d));
            var client = clientFabric.Client;

            var request = new RegistrationRequest()
            {
                Email       = login,
                Password    = login,
                IsAnonymous = true
            };
            TokenReply answer;

            try
            {
                answer = client.Register(request);
                Assert.False(string.IsNullOrWhiteSpace(answer.Token));
            }
            catch (RpcException e)
            {
                answer = new TokenReply();
                Assert.Equal(expected: StatusCode.AlreadyExists, e.StatusCode);
                Assert.False(string.IsNullOrEmpty(e.Message));
            }

            return(answer.Token);
        }
Ejemplo n.º 4
0
        public override async Task <TokenReply> GetToken(TokenRequest request, ServerCallContext context)
        {
            var        requestObject = new RequestObject <TokenRequest, TokenReply>(request);
            TokenReply reply         = await mediator.Send(requestObject).ConfigureAwait(false);

            if (requestObject.StatusCode != StatusCode.OK)
            {
                context.Status = new Status(requestObject.StatusCode, requestObject.Detail);
            }
            return(reply);
        }
Ejemplo n.º 5
0
        public async Task <IActionResult> Token([FromBody] TokenRequest request)
        {
            try
            {
                var        requestObject = new RequestObject <TokenRequest, TokenReply>(request);
                TokenReply reply         = await mediator.Send(requestObject).ConfigureAwait(false);

                return(Ok(reply));
            }
            catch (ArgumentException e)
            {
                return(BadRequest(e.Message));
            }
        }
        private Mock <IMemoryCache> CreateMockedCache(string key, TokenReply value, TestCacheEntry cacheEntry = null)
        {
            var mockCache    = new Mock <IMemoryCache>();
            var cachedObject = value as object;

            mockCache.Setup(c => c.TryGetValue("", out cachedObject))
            .Returns(false);

            mockCache.Setup(c => c.TryGetValue(key, out cachedObject))
            .Returns(true);

            mockCache.Setup(c => c.CreateEntry(_cacheKey))
            .Returns(cacheEntry);

            return(mockCache);
        }
Ejemplo n.º 7
0
        public override Task <TokenReply> GetToken(TokenRequest request, ServerCallContext context)
        {
            if (string.IsNullOrEmpty(request.Name))
            {
                throw new InvalidOperationException("Name is not specified.");
            }

            var claims       = new[] { new Claim(ClaimTypes.Name, request.Name) };
            var credentials  = new SigningCredentials(Security.SecurityKey, SecurityAlgorithms.HmacSha256);
            var token        = new JwtSecurityToken("Coding4Fun", "Coding4FunApp", claims, expires: DateTime.Now.AddSeconds(60), signingCredentials: credentials);
            var tokenCompact = Security.JwtTokenHandler.WriteToken(token);
            var response     = new TokenReply()
            {
                Token = tokenCompact
            };

            return(Task.FromResult(response));
        }
Ejemplo n.º 8
0
        private async Task <TokenReply> RetrieveToken(string clientID, string clientSecret, string scope, string tokenEndpoint)
        {
            TokenReply tokenReply = null;

            var content = $"client_id={clientID}&client_secret={clientSecret}&grant_type=client_credentials{(String.IsNullOrWhiteSpace(scope) ? "" : $"&scope={scope}")}";