public TokenValidator(
        IdentityServerOptions options,
        IIssuerNameService issuerNameService,
        IClientStore clients,
        IProfileService profile,
        IReferenceTokenStore referenceTokenStore,
        ICustomTokenValidator customValidator,
        IKeyMaterialService keys,
        ISessionCoordinationService sessionCoordinationService,
        ISystemClock clock,
        ILogger <TokenValidator> logger)
    {
        _options             = options;
        _issuerNameService   = issuerNameService;
        _clients             = clients;
        _profile             = profile;
        _referenceTokenStore = referenceTokenStore;
        _customValidator     = customValidator;
        _keys = keys;
        _sessionCoordinationService = sessionCoordinationService;
        _clock  = clock;
        _logger = logger;

        _log = new TokenValidationLog();
    }
 /// <summary>
 /// Instantiates an instance of private_key_jwt secret validator
 /// </summary>
 public JwtRequestValidator(IdentityServerOptions options, IIssuerNameService issuerNameService,
                            ILogger <JwtRequestValidator> logger)
 {
     Options           = options;
     IssuerNameService = issuerNameService;
     Logger            = logger;
 }
Exemple #3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CreatePersonalAccessTokenService"/> class.
 /// </summary>
 /// <param name="issuerNameService">The <see cref="IIssuerNameService"/></param>
 /// <param name="tokenService">The token service.</param>
 /// <param name="clientStore">The client store.</param>
 /// <param name="resourceStore">The resource store.</param>
 /// <exception cref="System.ArgumentNullException">
 /// tokenService
 /// or
 /// clientStore
 /// </exception>
 /// <exception cref="ArgumentNullException"></exception>
 public CreatePersonalAccessTokenService(IIssuerNameService issuerNameService, ITokenService tokenService, IClientStore clientStore, IResourceStore resourceStore)
 {
     _issuerNameService = issuerNameService ?? throw new ArgumentNullException(nameof(issuerNameService));
     _tokenService      = tokenService ?? throw new ArgumentNullException(nameof(tokenService));
     _clientStore       = clientStore ?? throw new ArgumentNullException(nameof(clientStore));
     _resourceStore     = resourceStore ?? throw new ArgumentNullException(nameof(resourceStore));
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="IdentityServerTools" /> class.
 /// </summary>
 /// <param name="serviceProvider">The provider.</param>
 /// <param name="issuerNameService">The issuer name service</param>
 /// <param name="tokenCreation">The token creation service.</param>
 /// <param name="clock">The clock.</param>
 public IdentityServerTools(IServiceProvider serviceProvider, IIssuerNameService issuerNameService, ITokenCreationService tokenCreation, ISystemClock clock)
 {
     ServiceProvider   = serviceProvider;
     IssuerNameService = issuerNameService;
     _tokenCreation    = tokenCreation;
     _clock            = clock;
 }
        /// <summary>
        /// Invokes the middleware.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="router">The router.</param>
        /// <param name="session">The user session.</param>
        /// <param name="events">The event service.</param>
        /// <param name="issuerNameService">The issuer name service</param>
        /// <param name="backChannelLogoutService"></param>
        /// <returns></returns>
        public async Task Invoke(
            HttpContext context,
            IEndpointRouter router,
            IUserSession session,
            IEventService events,
            IIssuerNameService issuerNameService,
            IBackChannelLogoutService backChannelLogoutService)
        {
            // this will check the authentication session and from it emit the check session
            // cookie needed from JS-based signout clients.
            await session.EnsureSessionIdCookieAsync();

            context.Response.OnStarting(async() =>
            {
                if (context.GetSignOutCalled())
                {
                    _logger.LogDebug("SignOutCalled set; processing post-signout session cleanup.");

                    // this clears our session id cookie so JS clients can detect the user has signed out
                    await session.RemoveSessionIdCookieAsync();

                    // back channel logout
                    var logoutContext = await session.GetLogoutNotificationContext();
                    if (logoutContext != null)
                    {
                        await backChannelLogoutService.SendLogoutNotificationsAsync(logoutContext);
                    }
                }
            });

            try
            {
                var endpoint = router.Find(context);
                if (endpoint != null)
                {
                    LicenseValidator.ValidateIssuer(await issuerNameService.GetCurrentAsync());

                    _logger.LogInformation("Invoking IdentityServer endpoint: {endpointType} for {url}", endpoint.GetType().FullName, context.Request.Path.ToString());

                    var result = await endpoint.ProcessAsync(context);

                    if (result != null)
                    {
                        _logger.LogTrace("Invoking result: {type}", result.GetType().FullName);
                        await result.ExecuteAsync(context);
                    }

                    return;
                }
            }
            catch (Exception ex)
            {
                await events.RaiseAsync(new UnhandledExceptionEvent(ex));

                _logger.LogCritical(ex, "Unhandled exception: {exception}", ex.Message);
                throw;
            }

            await _next(context);
        }
 public TokenRequestValidator(
     IdentityServerOptions options,
     IIssuerNameService issuerNameService,
     IAuthorizationCodeStore authorizationCodeStore,
     IResourceOwnerPasswordValidator resourceOwnerValidator,
     IProfileService profile,
     IDeviceCodeValidator deviceCodeValidator,
     IBackchannelAuthenticationRequestIdValidator backchannelAuthenticationRequestIdValidator,
     ExtensionGrantValidator extensionGrantValidator,
     ICustomTokenRequestValidator customRequestValidator,
     IResourceValidator resourceValidator,
     IResourceStore resourceStore,
     IRefreshTokenService refreshTokenService,
     IEventService events,
     ISystemClock clock,
     ILogger <TokenRequestValidator> logger)
 {
     _logger                 = logger;
     _options                = options;
     _issuerNameService      = issuerNameService;
     _clock                  = clock;
     _authorizationCodeStore = authorizationCodeStore;
     _resourceOwnerValidator = resourceOwnerValidator;
     _profile                = profile;
     _deviceCodeValidator    = deviceCodeValidator;
     _backchannelAuthenticationRequestIdValidator = backchannelAuthenticationRequestIdValidator;
     _extensionGrantValidator = extensionGrantValidator;
     _customRequestValidator  = customRequestValidator;
     _resourceValidator       = resourceValidator;
     _resourceStore           = resourceStore;
     _refreshTokenService     = refreshTokenService;
     _events = events;
 }
Exemple #7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="IdentityServerTools" /> class.
 /// </summary>
 /// <param name="contextAccessor">The context accessor.</param>
 /// <param name="issuerNameService">The issuer name service</param>
 /// <param name="tokenCreation">The token creation service.</param>
 /// <param name="clock">The clock.</param>
 public IdentityServerTools(IHttpContextAccessor contextAccessor, IIssuerNameService issuerNameService, ITokenCreationService tokenCreation, ISystemClock clock)
 {
     ContextAccessor   = contextAccessor;
     IssuerNameService = issuerNameService;
     _tokenCreation    = tokenCreation;
     _clock            = clock;
 }
 /// <summary>
 /// Ctor.
 /// </summary>
 public LogoutNotificationService(
     IClientStore clientStore,
     IIssuerNameService issuerNameService,
     ILogger <LogoutNotificationService> logger)
 {
     _clientStore       = clientStore;
     _issuerNameService = issuerNameService;
     _logger            = logger;
 }
 public BackchannelAuthenticationUserNotificationService(IIssuerNameService nameService,
                                                         IStringLocalizer <BackchannelAuthenticationUserNotificationService> localizer,
                                                         HttpClient httpClient,
                                                         IOptions <BackchannelAuthenticationUserNotificationServiceOptions> options)
 {
     _nameService = nameService ?? throw new ArgumentNullException(nameof(nameService));
     _localizer   = localizer ?? throw new ArgumentNullException(nameof(localizer));
     _httpClient  = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
     _options     = options ?? throw new ArgumentNullException(nameof(options));
 }
 public DiscoveryEndpoint(
     IdentityServerOptions options,
     IIssuerNameService issuerNameService,
     IDiscoveryResponseGenerator responseGenerator,
     ILogger <DiscoveryEndpoint> logger)
 {
     _logger            = logger;
     _options           = options;
     _issuerNameService = issuerNameService;
     _responseGenerator = responseGenerator;
 }
 /// <summary>
 /// Instantiates an instance of private_key_jwt secret validator
 /// </summary>
 public PrivateKeyJwtSecretValidator(
     IIssuerNameService issuerNameService,
     IReplayCache replayCache,
     IdentityServerOptions options,
     ILogger <PrivateKeyJwtSecretValidator> logger)
 {
     _issuerNameService = issuerNameService;
     _replayCache       = replayCache;
     _options           = options;
     _logger            = logger;
 }
Exemple #12
0
        /// <summary>
        /// Instantiates an instance of private_key_jwt secret validator
        /// </summary>
        public JwtRequestValidator(IdentityServerOptions options, IIssuerNameService issuerNameService,
                                   ILogger <JwtRequestValidator> logger)
        {
            Options           = options;
            IssuerNameService = issuerNameService;
            Logger            = logger;

            Handler = new JsonWebTokenHandler
            {
                MaximumTokenSizeInBytes = options.InputLengthRestrictions.Jwt
            };
        }
Exemple #13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SignInResponseGenerator"/> class.
 /// </summary>
 /// <param name="issuerNameService">The <see cref="IIssuerNameService"/>.</param>
 /// <param name="profile">The profile.</param>
 /// <param name="keys">The keys.</param>
 /// <param name="resources">The resources.</param>
 /// <param name="logger">The logger.</param>
 public SignInResponseGenerator(
     IIssuerNameService issuerNameService,
     IProfileService profile,
     ISigningCredentialStore keys,
     IResourceStore resources,
     ILogger <SignInResponseGenerator> logger)
 {
     _issuerNameService = issuerNameService ?? throw new ArgumentNullException(nameof(issuerNameService));
     _profile           = profile ?? throw new ArgumentNullException(nameof(profile));
     _keys      = keys ?? throw new ArgumentNullException(nameof(keys));
     _resources = resources ?? throw new ArgumentNullException(nameof(resources));
     _logger    = logger ?? throw new ArgumentNullException(nameof(logger));
 }
Exemple #14
0
 /// <summary>
 /// ctor
 /// </summary>
 /// <param name="options"></param>
 /// <param name="issuerNameService"></param>
 /// <param name="store"></param>
 /// <param name="dataProtectionProvider"></param>
 /// <param name="logger"></param>
 public ServerSideTicketService(
     IdentityServerOptions options,
     IIssuerNameService issuerNameService,
     IServerSideSessionStore store,
     IDataProtectionProvider dataProtectionProvider,
     ILogger <ServerSideTicketService> logger)
 {
     _options           = options;
     _issuerNameService = issuerNameService;
     _store             = store;
     _protector         = dataProtectionProvider.CreateProtector("Duende.SessionManagement.ServerSideTicketStore");
     _logger            = logger;
 }
Exemple #15
0
    public static TokenValidator CreateTokenValidator(
        IReferenceTokenStore store           = null,
        IRefreshTokenStore refreshTokenStore = null,
        IProfileService profile = null,
        IIssuerNameService issuerNameService = null,
        IdentityServerOptions options        = null,
        ISystemClock clock = null)
    {
        options ??= TestIdentityServerOptions.Create();
        profile ??= new TestProfileService();
        store ??= CreateReferenceTokenStore();
        clock ??= new StubClock();
        refreshTokenStore ??= CreateRefreshTokenStore();
        issuerNameService ??= new TestIssuerNameService(options.IssuerUri);

        var clients = CreateClientStore();

        var logger = TestLogger.Create <TokenValidator>();

        var keyInfo = new SecurityKeyInfo
        {
            Key = TestCert.LoadSigningCredentials().Key,
            SigningAlgorithm = "RS256"
        };

        var validator = new TokenValidator(
            clients: clients,
            clock: clock,
            profile: profile,
            referenceTokenStore: store,
            customValidator: new DefaultCustomTokenValidator(),
            keys: new DefaultKeyMaterialService(
                new[] { new InMemoryValidationKeysStore(new[] { keyInfo }) },
                Enumerable.Empty <ISigningCredentialStore>(),
                new NopAutomaticKeyManagerKeyStore()
                ),
            sessionCoordinationService: new StubSessionCoordinationService(),
            logger: logger,
            options: options,
            issuerNameService: issuerNameService);

        return(validator);
    }
        /// <summary>
        /// Constructor for KeyManager
        /// </summary>
        /// <param name="options"></param>
        /// <param name="store"></param>
        /// <param name="cache"></param>
        /// <param name="protector"></param>
        /// <param name="clock"></param>
        /// <param name="newKeyLock"></param>
        /// <param name="logger"></param>
        /// <param name="issuerNameService"></param>
        public KeyManager(
            KeyManagementOptions options,
            ISigningKeyStore store,
            ISigningKeyStoreCache cache,
            ISigningKeyProtector protector,
            ISystemClock clock,
            INewKeyLock newKeyLock,
            ILogger <KeyManager> logger,
            IIssuerNameService issuerNameService)
        {
            options.Validate();

            _options           = options;
            _store             = store;
            _cache             = cache;
            _protector         = protector;
            _clock             = clock;
            _newKeyLock        = newKeyLock;
            _logger            = logger;
            _issuerNameService = issuerNameService;
        }
Exemple #17
0
 public AuthorizeRequestValidator(
     IdentityServerOptions options,
     IIssuerNameService issuerNameService,
     IClientStore clients,
     ICustomAuthorizeRequestValidator customValidator,
     IRedirectUriValidator uriValidator,
     IResourceValidator resourceValidator,
     IUserSession userSession,
     JwtRequestValidator jwtRequestValidator,
     IJwtRequestUriHttpClient jwtRequestUriHttpClient,
     ILogger <AuthorizeRequestValidator> logger)
 {
     _options                 = options;
     _issuerNameService       = issuerNameService;
     _clients                 = clients;
     _customValidator         = customValidator;
     _uriValidator            = uriValidator;
     _resourceValidator       = resourceValidator;
     _jwtRequestValidator     = jwtRequestValidator;
     _userSession             = userSession;
     _jwtRequestUriHttpClient = jwtRequestUriHttpClient;
     _logger = logger;
 }
Exemple #18
0
        public static TokenRequestValidator CreateTokenRequestValidator(
            IdentityServerOptions options                          = null,
            IIssuerNameService issuerNameService                   = null,
            IResourceStore resourceStore                           = null,
            IAuthorizationCodeStore authorizationCodeStore         = null,
            IRefreshTokenStore refreshTokenStore                   = null,
            IResourceOwnerPasswordValidator resourceOwnerValidator = null,
            IProfileService profile = null,
            IDeviceCodeValidator deviceCodeValidator = null,
            IEnumerable <IExtensionGrantValidator> extensionGrantValidators = null,
            ICustomTokenRequestValidator customRequestValidator             = null,
            IRefreshTokenService refreshTokenService = null,
            IResourceValidator resourceValidator     = null)
        {
            if (options == null)
            {
                options = TestIdentityServerOptions.Create();
            }

            if (issuerNameService == null)
            {
                issuerNameService = new TestIssuerNameService(options.IssuerUri);
            }

            if (resourceStore == null)
            {
                resourceStore = new InMemoryResourcesStore(TestScopes.GetIdentity(), TestScopes.GetApis(), TestScopes.GetScopes());
            }

            if (resourceOwnerValidator == null)
            {
                resourceOwnerValidator = new TestResourceOwnerPasswordValidator();
            }

            if (profile == null)
            {
                profile = new TestProfileService();
            }

            if (deviceCodeValidator == null)
            {
                deviceCodeValidator = new TestDeviceCodeValidator();
            }

            if (customRequestValidator == null)
            {
                customRequestValidator = new DefaultCustomTokenRequestValidator();
            }

            ExtensionGrantValidator aggregateExtensionGrantValidator;

            if (extensionGrantValidators == null)
            {
                aggregateExtensionGrantValidator = new ExtensionGrantValidator(new[] { new TestGrantValidator() }, TestLogger.Create <ExtensionGrantValidator>());
            }
            else
            {
                aggregateExtensionGrantValidator = new ExtensionGrantValidator(extensionGrantValidators, TestLogger.Create <ExtensionGrantValidator>());
            }

            if (authorizationCodeStore == null)
            {
                authorizationCodeStore = CreateAuthorizationCodeStore();
            }

            if (refreshTokenStore == null)
            {
                refreshTokenStore = CreateRefreshTokenStore();
            }

            if (resourceValidator == null)
            {
                resourceValidator = CreateResourceValidator(resourceStore);
            }

            if (refreshTokenService == null)
            {
                refreshTokenService = CreateRefreshTokenService(
                    refreshTokenStore,
                    profile);
            }

            return(new TokenRequestValidator(
                       options,
                       issuerNameService,
                       authorizationCodeStore,
                       resourceOwnerValidator,
                       profile,
                       deviceCodeValidator,
                       aggregateExtensionGrantValidator,
                       customRequestValidator,
                       resourceValidator,
                       resourceStore,
                       refreshTokenService,
                       new TestEventService(),
                       new StubClock(),
                       TestLogger.Create <TokenRequestValidator>()));
        }
Exemple #19
0
        public static AuthorizeRequestValidator CreateAuthorizeRequestValidator(
            IdentityServerOptions options        = null,
            IIssuerNameService issuerNameService = null,
            IResourceStore resourceStore         = null,
            IClientStore clients    = null,
            IProfileService profile = null,
            ICustomAuthorizeRequestValidator customValidator = null,
            IRedirectUriValidator uriValidator               = null,
            IResourceValidator resourceValidator             = null,
            JwtRequestValidator jwtRequestValidator          = null,
            IJwtRequestUriHttpClient jwtRequestUriHttpClient = null)
        {
            if (options == null)
            {
                options = TestIdentityServerOptions.Create();
            }

            if (issuerNameService == null)
            {
                issuerNameService = new TestIssuerNameService(options.IssuerUri);
            }

            if (resourceStore == null)
            {
                resourceStore = new InMemoryResourcesStore(TestScopes.GetIdentity(), TestScopes.GetApis(), TestScopes.GetScopes());
            }

            if (clients == null)
            {
                clients = new InMemoryClientStore(TestClients.Get());
            }

            if (customValidator == null)
            {
                customValidator = new DefaultCustomAuthorizeRequestValidator();
            }

            if (uriValidator == null)
            {
                uriValidator = new StrictRedirectUriValidator();
            }

            if (resourceValidator == null)
            {
                resourceValidator = CreateResourceValidator(resourceStore);
            }

            if (jwtRequestValidator == null)
            {
                jwtRequestValidator = new JwtRequestValidator("https://identityserver", new LoggerFactory().CreateLogger <JwtRequestValidator>());
            }

            if (jwtRequestUriHttpClient == null)
            {
                jwtRequestUriHttpClient = new DefaultJwtRequestUriHttpClient(new HttpClient(new NetworkHandler(new Exception("no jwt request uri response configured"))), options, new LoggerFactory());
            }


            var userSession = new MockUserSession();

            return(new AuthorizeRequestValidator(
                       options,
                       issuerNameService,
                       clients,
                       customValidator,
                       uriValidator,
                       resourceValidator,
                       userSession,
                       jwtRequestValidator,
                       jwtRequestUriHttpClient,
                       TestLogger.Create <AuthorizeRequestValidator>()));
        }
 /// <summary>
 /// Ctor
 /// </summary>
 public NopBackchannelAuthenticationUserNotificationService(IIssuerNameService issuerNameService, ILogger <NopBackchannelAuthenticationUserNotificationService> logger)
 {
     _issuerNameService = issuerNameService;
     _logger            = logger;
 }
Exemple #21
0
    /// <summary>
    /// Invokes the middleware.
    /// </summary>
    /// <param name="context">The context.</param>
    /// <param name="router">The router.</param>
    /// <param name="userSession">The user session.</param>
    /// <param name="events">The event service.</param>
    /// <param name="issuerNameService">The issuer name service</param>
    /// <param name="sessionCoordinationService"></param>
    /// <returns></returns>
    public async Task Invoke(
        HttpContext context,
        IEndpointRouter router,
        IUserSession userSession,
        IEventService events,
        IIssuerNameService issuerNameService,
        ISessionCoordinationService sessionCoordinationService)
    {
        // this will check the authentication session and from it emit the check session
        // cookie needed from JS-based signout clients.
        await userSession.EnsureSessionIdCookieAsync();

        context.Response.OnStarting(async() =>
        {
            if (context.GetSignOutCalled())
            {
                _logger.LogDebug("SignOutCalled set; processing post-signout session cleanup.");

                // this clears our session id cookie so JS clients can detect the user has signed out
                await userSession.RemoveSessionIdCookieAsync();

                var user = await userSession.GetUserAsync();
                if (user != null)
                {
                    var session = new UserSession
                    {
                        SubjectId   = user.GetSubjectId(),
                        SessionId   = await userSession.GetSessionIdAsync(),
                        DisplayName = user.GetDisplayName(),
                        ClientIds   = (await userSession.GetClientListAsync()).ToList(),
                        Issuer      = await issuerNameService.GetCurrentAsync()
                    };
                    await sessionCoordinationService.ProcessLogoutAsync(session);
                }
            }
        });

        try
        {
            var endpoint = router.Find(context);
            if (endpoint != null)
            {
                var endpointType = endpoint.GetType().FullName;

                using var activity = Tracing.BasicActivitySource.StartActivity("IdentityServerProtocolRequest");
                activity?.SetTag(Tracing.Properties.EndpointType, endpointType);

                LicenseValidator.ValidateIssuer(await issuerNameService.GetCurrentAsync());

                _logger.LogInformation("Invoking IdentityServer endpoint: {endpointType} for {url}", endpointType, context.Request.Path.ToString());

                var result = await endpoint.ProcessAsync(context);

                if (result != null)
                {
                    _logger.LogTrace("Invoking result: {type}", result.GetType().FullName);
                    await result.ExecuteAsync(context);
                }

                return;
            }
        }
        catch (Exception ex)
        {
            await events.RaiseAsync(new UnhandledExceptionEvent(ex));

            _logger.LogCritical(ex, "Unhandled exception: {exception}", ex.Message);
            throw;
        }

        await _next(context);
    }
 /// <summary>
 /// Initializes a new instance of the <see cref="MetadataResponseGenerator"/> class.
 /// </summary>
 /// <param name="issuerNameService">The <see cref="IIssuerNameService"/>.</param>
 /// <param name="keys">The keys.</param>
 public MetadataResponseGenerator(IIssuerNameService issuerNameService, ISigningCredentialStore keys)
 {
     _keys = keys;
     _issuerNameService = issuerNameService;
 }
 /// <summary>
 /// Instantiates an instance of private_key_jwt secret validator
 /// </summary>
 public PrivateKeyJwtSecretValidator(IIssuerNameService issuerNameService, IReplayCache replayCache, ILogger <PrivateKeyJwtSecretValidator> logger)
 {
     _issuerNameService = issuerNameService;
     _replayCache       = replayCache;
     _logger            = logger;
 }