public FakedAuthenticationProvider(IClaimsIdentityProvider claimsIdentityProvider)
        {
            _namespacePrefixes = new Lazy <List <string> >(() => new List <string> {
                "uri://ed-fi.org"
            });
            _educationOrganizationIds = new Lazy <List <int> >(() => new List <int> {
                255901
            });

            _identity = new Lazy <ClaimsIdentity>(
                () => claimsIdentityProvider
                .GetClaimsIdentity(
                    _educationOrganizationIds.Value, ClaimSetName, _namespacePrefixes.Value, new List <string>()));

            _apiKeyContext = new Lazy <ApiKeyContext>(
                () => new ApiKeyContext(
                    Guid.NewGuid().ToString("n"),
                    ClaimSetName,
                    _educationOrganizationIds.Value,
                    _namespacePrefixes.Value,
                    null,
                    null,
                    null,
                    null));
        }
        /// <summary>
        /// Implements the signature needed by the <see cref="ClaimsPrincipal.ClaimsPrincipalSelector"/> static delegate for
        /// obtaining <see cref="ClaimsPrincipal"/> instances.
        /// </summary>
        /// <returns>The <see cref="ClaimsPrincipal"/> that can be used to make authorization decisions.</returns>
        public static ClaimsPrincipal GetClaimsPrincipal(IClaimsIdentityProvider identityProvider)
        {
            // If we've already establish the OAuth-based claims principal on this thread, return it.
            if (Thread.CurrentPrincipal.Identity.AuthenticationType == EdFiAuthenticationTypes.OAuth)
            {
                return(Thread.CurrentPrincipal as ClaimsPrincipal);
            }

            // Establish the ClaimsPrincipal based on the current context
            var claimsIdentity = identityProvider.GetClaimsIdentity();

            return(new ClaimsPrincipal(claimsIdentity));
        }
Exemplo n.º 3
0
        public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            // TODO: Go to database to verify.
            if (context.UserName != context.Password)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect");
                return(Task.FromResult(0));
            }

            // If still here we have validated the credentials. Lets proceed to issue claims.
            var userId = "55";

            var identity = _claimsIdentityProvider.GetClaimsIdentity(userId);

            context.Validated(identity);
            return(Task.FromResult(0));
        }
Exemplo n.º 4
0
        public string GetToken(string user, DateTime?expires)
        {
            var handler = new JwtSecurityTokenHandler();

            var identity = _claimsIdentityProvider.GetClaimsIdentity("abc123");

            var securityTokenDescriptor = new SecurityTokenDescriptor
            {
                // Issuer
                TokenIssuerName = _applicationSettingsProvider.GetValue("JWT.Issuer"),

                //Audience = tokenOptions.Audience,
                AppliesToAddress   = _applicationSettingsProvider.GetValue("JWT.Audience"), // Audience
                SigningCredentials = _signingCredentialsProvider.GetSigningCredentials(),
                Subject            = identity,
                //Expires = expires
                Lifetime = new Lifetime(DateTime.Now, expires)
            };

            var securityToken = handler.CreateToken(securityTokenDescriptor);

            return(handler.WriteToken(securityToken));
        }
        public async Task <AuthenticationResult> GetAuthenticationResultAsync(AuthenticationHeaderValue authHeader)
        {
            ApiClientDetails apiClientDetails;

            try
            {
                // If there are credentials but the filter does not recognize the authentication scheme, do nothing.
                if (!authHeader.Scheme.EqualsIgnoreCase(AuthenticationScheme))
                {
                    _logger.Debug("Unknown auth header scheme");
                    return(new AuthenticationResult {
                        AuthenticateResult = AuthenticateResult.NoResult()
                    });
                }

                // If the credentials are bad, set the error result.
                if (string.IsNullOrEmpty(authHeader.Parameter))
                {
                    _logger.Debug("Missing auth header parameter");

                    return(new AuthenticationResult
                    {
                        AuthenticateResult = AuthenticateResult.Fail("Missing auth header parameter")
                    });
                }

                // If there are credentials that the filter understands, try to validate them.
                apiClientDetails = await _oAuthTokenValidator.GetClientDetailsForTokenAsync(authHeader.Parameter);
            }
            catch (Exception e)
            {
                _logger.Error(e);
                return(new AuthenticationResult {
                    AuthenticateResult = AuthenticateResult.Fail("Invalid Authorization Header")
                });
            }

            if (_expectedUseSandboxValue.Value.HasValue &&
                apiClientDetails.IsSandboxClient != _expectedUseSandboxValue.Value.Value)
            {
                string message = apiClientDetails.IsSandboxClient
                    ? "Sandbox credentials used in call to Production API"
                    : "Production credentials used in call to Sandbox API";

                return(new AuthenticationResult {
                    AuthenticateResult = AuthenticateResult.Fail(message)
                });
            }

            var identity = _claimsIdentityProvider.GetClaimsIdentity(
                apiClientDetails.EducationOrganizationIds,
                apiClientDetails.ClaimSetName,
                apiClientDetails.NamespacePrefixes,
                apiClientDetails.Profiles.ToList());

            var apiKeyContext = new ApiKeyContext(
                apiClientDetails.ApiKey,
                apiClientDetails.ClaimSetName,
                apiClientDetails.EducationOrganizationIds,
                apiClientDetails.NamespacePrefixes,
                apiClientDetails.Profiles,
                apiClientDetails.StudentIdentificationSystemDescriptor,
                apiClientDetails.CreatorOwnershipTokenId,
                apiClientDetails.OwnershipTokenIds);

            return(new AuthenticationResult
            {
                ClaimsIdentity = identity,
                ApiKeyContext = apiKeyContext
            });
        }
Exemplo n.º 6
0
        /// <inheritdoc cref="IOAuthTokenAuthenticator.AuthenticateAsync" />
        public async Task <AuthenticateResult> AuthenticateAsync(string token, string authorizationScheme)
        {
            ApiClientDetails apiClientDetails;

            try
            {
                // If there are credentials that the filter understands, try to validate them.
                apiClientDetails = await _apiClientDetailsProvider.GetClientDetailsForTokenAsync(token);

                if (!apiClientDetails.IsTokenValid)
                {
                    return(AuthenticateResult.Fail("Invalid token"));
                }
            }
            catch (Exception e)
            {
                _logger.Error(e);
                return(AuthenticateResult.Fail("Invalid Authorization Header"));
            }

            if (_expectedUseSandboxValue.Value.HasValue &&
                apiClientDetails.IsSandboxClient != _expectedUseSandboxValue.Value.Value)
            {
                string message = apiClientDetails.IsSandboxClient
                    ? "Sandbox credentials used in call to Production API"
                    : "Production credentials used in call to Sandbox API";

                return(AuthenticateResult.Fail(message));
            }

            var identity = _claimsIdentityProvider.GetClaimsIdentity(
                apiClientDetails.EducationOrganizationIds,
                apiClientDetails.ClaimSetName,
                apiClientDetails.NamespacePrefixes,
                apiClientDetails.Profiles.ToList(),
                apiClientDetails.OwnershipTokenIds.ToList());

            var principal = new ClaimsPrincipal(identity);
            var ticket    = new AuthenticationTicket(principal, CreateAuthenticationProperties(), authorizationScheme);

            return(AuthenticateResult.Success(ticket));

            AuthenticationProperties CreateAuthenticationProperties()
            {
                var parameters = new Dictionary <string, object>()
                {
                    {
                        "ApiKeyContext",
                        new ApiKeyContext(
                            apiClientDetails.ApiKey,
                            apiClientDetails.ClaimSetName,
                            apiClientDetails.EducationOrganizationIds,
                            apiClientDetails.NamespacePrefixes,
                            apiClientDetails.Profiles,
                            apiClientDetails.StudentIdentificationSystemDescriptor,
                            apiClientDetails.CreatorOwnershipTokenId,
                            apiClientDetails.OwnershipTokenIds)
                    }
                };

                var items = new Dictionary <string, string>()
                {
                    { ".expires", apiClientDetails.ExpiresUtc.ToString("O") }
                };

                return(new AuthenticationProperties(items, parameters));
            }
        }