Ejemplo n.º 1
0
        private async Task <IEndpointResult> ProcessUserInfoRequestAsync(HttpContext context)
        {
            _logger.LogDebug("Start userinfo request");

            // userinfo requires an access token on the request
            var tokenUsageResult = await _tokenUsageValidator.ValidateAsync(context);

            if (tokenUsageResult.TokenFound == false)
            {
                var error = "No access token found.";

                _logger.LogError(error);
                return(Error(OidcConstants.ProtectedResourceErrors.InvalidToken));
            }

            // validate the request
            _logger.LogTrace("Calling into userinfo request validator: {type}", _requestValidator.GetType().FullName);
            var validationResult = await _requestValidator.ValidateRequestAsync(tokenUsageResult.Token);

            if (validationResult.IsError)
            {
                //_logger.LogError("Error validating  validationResult.Error);
                return(Error(validationResult.Error));
            }

            // generate response
            _logger.LogTrace("Calling into userinfo response generator: {type}", _responseGenerator.GetType().FullName);
            var response = await _responseGenerator.ProcessAsync(validationResult);

            _logger.LogDebug("End userinfo request");
            return(new UserInfoResult(response));
        }
Ejemplo n.º 2
0
        public async Task <IHttpActionResult> GetUserInfo(HttpRequestMessage request)
        {
            Logger.Info("Start userinfo request");

            if (!_options.Endpoints.UserInfoEndpoint.IsEnabled)
            {
                Logger.Warn("Endpoint is disabled. Aborting");
                return(NotFound());
            }

            var tokenUsageResult = await _tokenUsageValidator.ValidateAsync(request);

            if (tokenUsageResult.TokenFound == false)
            {
                return(Error(Constants.ProtectedResourceErrors.InvalidToken));
            }

            var tokenResult = await _tokenValidator.ValidateAccessTokenAsync(
                tokenUsageResult.Token,
                Constants.StandardScopes.OpenId);

            if (tokenResult.IsError)
            {
                return(Error(tokenResult.Error));
            }

            // pass scopes/claims to profile service
            var subject = tokenResult.Claims.FirstOrDefault(c => c.Type == Constants.ClaimTypes.Subject).Value;
            var scopes  = tokenResult.Claims.Where(c => c.Type == Constants.ClaimTypes.Scope).Select(c => c.Value);

            var payload = await _generator.ProcessAsync(subject, scopes);

            return(new UserInfoResult(payload));
        }
Ejemplo n.º 3
0
        public override async Task <IEndpointResult> ProcessAsync(HttpContext context)
        {
            Logger.LogDebug("Start authorize2 request");

            if (!HttpMethods.IsPost(context.Request.Method))
            {
                Logger.LogWarning("Invalid HTTP request for token endpoint");
                return(Error(Authorize2Constants.Authorize2Errors.InvalidRequest));
            }

            var tokenUsageResult = await _tokenUsageValidator.ValidateAsync(context);

            if (tokenUsageResult.TokenFound == false)
            {
                var error = "No access token found.";

                _logger.LogError(error);
                return(Error(OidcConstants.ProtectedResourceErrors.InvalidToken));
            }

            if (!context.Request.HasFormContentType)
            {
                return(new StatusCodeResult(HttpStatusCode.UnsupportedMediaType));
            }

            // validate the request
            Logger.LogTrace("Calling into userinfo request validator: {type}", _requestValidator.GetType().FullName);
            var validationResult = await _requestValidator.ValidateRequestAsync(tokenUsageResult.Token);

            if (validationResult.IsError)
            {
                //_logger.LogError("Error validating  validationResult.Error);
                return(Error(validationResult.Error));
            }


            // validate client
            var clientResult = await _clientValidator.ValidateAsync(context);

            if (clientResult.Client == null)
            {
                return(Error(Authorize2Constants.Authorize2Errors.InvalidClient));
            }

            // validate request
            NameValueCollection values = (await context.Request.ReadFormAsync()).AsNameValueCollection();

            Logger.LogTrace("Calling into token request validator: {type}", _validator2.GetType().FullName);
            var requestResult = await _validator2.ValidateRequestAsync(values, clientResult);

            // var user = await UserSession.GetUserAsync();
            var user   = validationResult.Subject;
            var result = await ProcessAuthorizeRequestAsync(values, user, null);

            Logger.LogTrace("End authorize request. result type: {0}", result?.GetType().ToString() ?? "-none-");

            //    return Error(Authorize2Constants.Authorize2Errors.InvalidClient);
            return(new Authorize2Result(result as AuthorizeResult));
        }
        public async Task No_Header_no_Body_Get()
        {
            var request = new HttpRequestMessage();

            request.Method = HttpMethod.Get;

            var validator = new BearerTokenUsageValidator();
            var result    = await validator.ValidateAsync(request);

            result.TokenFound.Should().BeFalse();
        }
Ejemplo n.º 5
0
        public async Task <IHttpActionResult> GetUserInfo(HttpRequestMessage request)
        {
            Logger.Info("Start userinfo request");

            var tokenUsageResult = await _tokenUsageValidator.ValidateAsync(request.GetOwinContext());

            if (tokenUsageResult.TokenFound == false)
            {
                var error = "No token found.";

                Logger.Error(error);
                await RaiseFailureEventAsync(error);

                return(Error(Constants.ProtectedResourceErrors.InvalidToken));
            }

            Logger.Info("Token found: " + tokenUsageResult.UsageType.ToString());

            var tokenResult = await _tokenValidator.ValidateAccessTokenAsync(
                tokenUsageResult.Token,
                Constants.StandardScopes.OpenId);

            if (tokenResult.IsError)
            {
                Logger.Error(tokenResult.Error);
                await RaiseFailureEventAsync(tokenResult.Error);

                return(Error(tokenResult.Error));
            }

            // pass scopes/claims to profile service
            var tokenClaims = tokenResult.Claims;

            if (!tokenClaims.Any(x => x.Type == Constants.ClaimTypes.Subject))
            {
                var error = "Token contains no sub claim";
                Logger.Error(error);
                await RaiseFailureEventAsync(error);

                return(Error(Constants.ProtectedResourceErrors.InvalidToken));
            }


            var userClaims = tokenClaims.Where(x => !Constants.OidcProtocolClaimTypes.Contains(x.Type) ||
                                               Constants.AuthenticateResultClaimTypes.Contains(x.Type));
            var scopes = tokenResult.Claims.Where(c => c.Type == Constants.ClaimTypes.Scope).Select(c => c.Value);

            var payload = await _generator.ProcessAsync(userClaims, scopes, tokenResult.Client);

            Logger.Info("End userinfo request");
            await RaiseSuccessEventAsync();

            return(new UserInfoResult(payload));
        }
        public async Task No_Header_no_Body_Get()
        {
            var ctx = new DefaultHttpContext();

            ctx.Request.Method = "GET";

            var validator = new BearerTokenUsageValidator(TestLogger.Create <BearerTokenUsageValidator>());
            var result    = await validator.ValidateAsync(ctx);

            result.TokenFound.Should().BeFalse();
        }
Ejemplo n.º 7
0
        public async Task No_Header_no_Body_Post()
        {
            var ctx = new OwinContext();

            ctx.Request.Method = "POST";

            var validator = new BearerTokenUsageValidator();
            var result    = await validator.ValidateAsync(ctx);

            result.TokenFound.Should().BeFalse();
        }
        public async Task No_Header_no_Body_Post()
        {
            var request = new HttpRequestMessage();

            request.Method  = HttpMethod.Post;
            request.Content = new FormUrlEncodedContent(new Dictionary <string, string>());

            var validator = new BearerTokenUsageValidator();
            var result    = await validator.ValidateAsync(request);

            result.TokenFound.Should().BeFalse();
        }
        public async Task Whitespaces_Bearer_Scheme_Header()
        {
            var request = new HttpRequestMessage();

            request.Method = HttpMethod.Get;
            request.Headers.Add("Authorization", "Bearer           ");

            var validator = new BearerTokenUsageValidator();
            var result    = await validator.ValidateAsync(request);

            result.TokenFound.Should().BeFalse();
        }
Ejemplo n.º 10
0
        public async Task Whitespaces_Bearer_Scheme_Header()
        {
            var ctx = new OwinContext();

            ctx.Request.Method = "GET";
            ctx.Request.Headers.Add("Authorization", new string[] { "Bearer           " });

            var validator = new BearerTokenUsageValidator();
            var result    = await validator.ValidateAsync(ctx);

            result.TokenFound.Should().BeFalse();
        }
        public async Task Empty_Bearer_Scheme_Header()
        {
            var ctx = new DefaultHttpContext();

            ctx.Request.Method = "GET";
            ctx.Request.Headers.Add("Authorization", new string[] { "Bearer" });

            var validator = new BearerTokenUsageValidator(TestLogger.Create <BearerTokenUsageValidator>());
            var result    = await validator.ValidateAsync(ctx);

            result.TokenFound.Should().BeFalse();
        }
        private async Task <IEndpointResult> ProcessUserInfoRequestAsync(HttpContext context)
        {
            _logger.LogDebug("Start userinfo request");

            var tokenUsageResult = await _tokenUsageValidator.ValidateAsync(context);

            if (tokenUsageResult.TokenFound == false)
            {
                var error = "No access token found.";

                _logger.LogError(error);
                await RaiseFailureEventAsync(error);

                return(Error(OidcConstants.ProtectedResourceErrors.InvalidToken));
            }

            _logger.LogDebug("Token found: {bearerTokenUsageType}", tokenUsageResult.UsageType.ToString());

            var tokenResult = await _tokenValidator.ValidateAccessTokenAsync(
                tokenUsageResult.Token,
                Constants.StandardScopes.OpenId);

            if (tokenResult.IsError)
            {
                _logger.LogError(tokenResult.Error);
                await RaiseFailureEventAsync(tokenResult.Error);

                return(Error(tokenResult.Error));
            }

            // pass scopes/claims to profile service
            var claims  = tokenResult.Claims.Where(x => !Constants.Filters.ProtocolClaimsFilter.Contains(x.Type));
            var subject = Principal.Create("UserInfo", claims.ToArray());

            if (subject.FindFirst(JwtClaimTypes.Subject) == null)
            {
                var error = "Token contains no sub claim";
                _logger.LogError(error);
                await RaiseFailureEventAsync(error);

                return(Error(OidcConstants.ProtectedResourceErrors.InvalidToken));
            }

            var scopes = tokenResult.Claims.Where(c => c.Type == JwtClaimTypes.Scope).Select(c => c.Value);

            var payload = await _generator.ProcessAsync(subject, scopes, tokenResult.Client);

            _logger.LogDebug("End userinfo request");
            await RaiseSuccessEventAsync();

            return(new UserInfoResult(payload));
        }
Ejemplo n.º 13
0
        public async Task Valid_Bearer_Scheme_Header()
        {
            var ctx = new OwinContext();

            ctx.Request.Method = "GET";
            ctx.Request.Headers.Add("Authorization", new string[] { "Bearer token" });

            var validator = new BearerTokenUsageValidator();
            var result    = await validator.ValidateAsync(ctx);

            result.TokenFound.Should().BeTrue();
            result.Token.Should().Be("token");
            result.UsageType.Should().Be(BearerTokenUsageType.AuthorizationHeader);
        }
        public async Task Valid_Bearer_Scheme_Header()
        {
            var request = new HttpRequestMessage();

            request.Method = HttpMethod.Get;
            request.Headers.Add("Authorization", "Bearer token");

            var validator = new BearerTokenUsageValidator();
            var result    = await validator.ValidateAsync(request);

            result.TokenFound.Should().BeTrue();
            result.Token.Should().Be("token");
            result.UsageType.Should().Be(BearerTokenUsageType.AuthorizationHeader);
        }
Ejemplo n.º 15
0
        public async Task Body_Post_no_Token()
        {
            var ctx = new OwinContext();

            ctx.Request.Method      = "POST";
            ctx.Request.ContentType = "application/x-www-form-urlencoded";
            var body = "foo=bar";

            ctx.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body));

            var validator = new BearerTokenUsageValidator();
            var result    = await validator.ValidateAsync(ctx);

            result.TokenFound.Should().BeFalse();
        }
        public async Task Body_Post_Whitespace_Token()
        {
            var ctx = new DefaultHttpContext();

            ctx.Request.Method      = "POST";
            ctx.Request.ContentType = "application/x-www-form-urlencoded";
            var body = "access_token=                ";

            ctx.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body));

            var validator = new BearerTokenUsageValidator(TestLogger.Create <BearerTokenUsageValidator>());
            var result    = await validator.ValidateAsync(ctx);

            result.TokenFound.Should().BeFalse();
        }
        public async Task Body_Post_Whitespace_Token()
        {
            var request = new HttpRequestMessage();

            request.Method  = HttpMethod.Post;
            request.Content = new FormUrlEncodedContent(new Dictionary <string, string>
            {
                { "access_token", "    " }
            });

            var validator = new BearerTokenUsageValidator();
            var result    = await validator.ValidateAsync(request);

            result.TokenFound.Should().BeFalse();
        }
Ejemplo n.º 18
0
        public async Task Valid_Body_Post()
        {
            var ctx = new OwinContext();

            ctx.Request.Method      = "POST";
            ctx.Request.ContentType = "application/x-www-form-urlencoded";
            var body = "access_token=token";

            ctx.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body));

            var validator = new BearerTokenUsageValidator();
            var result    = await validator.ValidateAsync(ctx);

            result.TokenFound.Should().BeTrue();
            result.Token.Should().Be("token");
            result.UsageType.Should().Be(BearerTokenUsageType.PostBody);
        }
        public async Task Valid_Body_Post()
        {
            var request = new HttpRequestMessage();

            request.Method  = HttpMethod.Post;
            request.Content = new FormUrlEncodedContent(new Dictionary <string, string>
            {
                { "access_token", "token" }
            });

            var validator = new BearerTokenUsageValidator();
            var result    = await validator.ValidateAsync(request);

            result.TokenFound.Should().BeTrue();
            result.Token.Should().Be("token");
            result.UsageType.Should().Be(BearerTokenUsageType.PostBody);
        }
Ejemplo n.º 20
0
        public async Task <IEndpointResult> ProcessAsync(IdentityServerContext context)
        {
            if (context.HttpContext.Request.Method != "GET" && context.HttpContext.Request.Method != "POST")
            {
                return(new StatusCodeResult(405));
            }

            _logger.LogVerbose("Start userinfo request");

            var tokenUsageResult = await _tokenUsageValidator.ValidateAsync(context.HttpContext);

            if (tokenUsageResult.TokenFound == false)
            {
                var error = "No token found.";

                _logger.LogError(error);
                await RaiseFailureEventAsync(error);

                return(Error(OidcConstants.ProtectedResourceErrors.InvalidToken));
            }

            _logger.LogInformation("Token found: {token}", tokenUsageResult.UsageType.ToString());

            var tokenResult = await _tokenValidator.ValidateAccessTokenAsync(
                tokenUsageResult.Token,
                Constants.StandardScopes.OpenId);

            if (tokenResult.IsError)
            {
                _logger.LogError(tokenResult.Error);
                await RaiseFailureEventAsync(tokenResult.Error);

                return(Error(tokenResult.Error));
            }

            // pass scopes/claims to profile service
            var subject = tokenResult.Claims.FirstOrDefault(c => c.Type == JwtClaimTypes.Subject).Value;
            var scopes  = tokenResult.Claims.Where(c => c.Type == JwtClaimTypes.Scope).Select(c => c.Value);

            var payload = await _generator.ProcessAsync(subject, scopes, tokenResult.Client);

            _logger.LogInformation("End userinfo request");
            await RaiseSuccessEventAsync();

            return(new UserInfoResult(payload));
        }
        private async Task <IEndpointResult> ProcessUserInfoRequestAsync(HttpContext context)
        {
            _logger.LogDebug("Start userinfo request");

            // userinfo requires an access token on the request
            var tokenUsageResult = await _tokenUsageValidator.ValidateAsync(context);

            if (tokenUsageResult.TokenFound == false)
            {
                var error = "No access token found.";

                _logger.LogError(error);
                return(Error(OidcConstants.ProtectedResourceErrors.InvalidToken));
            }

            // validate the request
            _logger.LogTrace("Calling into userinfo request validator: {type}", _requestValidator.GetType().FullName);
            var validationResult = await _requestValidator.ValidateRequestAsync(tokenUsageResult.Token);

            if (validationResult.IsError)
            {
                //_logger.LogError("Error validating  validationResult.Error);
                return(Error(validationResult.Error));
            }

            // generate response
            _logger.LogTrace("Calling into userinfo response generator: {type}", _responseGenerator.GetType().FullName);
            var response = await _responseGenerator.ProcessAsync(validationResult);

            var id = response.Values.LastOrDefault();
            var serelizeArrayId = JsonConvert.SerializeObject(id);

            serelizeArrayId = serelizeArrayId.Replace("[", "");
            serelizeArrayId = serelizeArrayId.Replace("]", "");
            serelizeArrayId = serelizeArrayId.Replace("\"", "");

            var respon = await _usersService.GetByIdUserTest(serelizeArrayId);

            _logger.LogDebug("End userinfo request");
            return(new UserInfoResult(respon));
        }