/// <summary>
        /// Initializes a new instance of the <see cref="InMemoryValidationResultCache"/> class.
        /// </summary>
        /// <param name="options">The options.</param>
        /// <param name="clock">The clock.</param>
        /// <param name="cache">The cache.</param>
        /// <exception cref="System.ArgumentNullException">
        /// clock
        /// or
        /// options
        /// or
        /// cache
        /// </exception>
	    public InMemoryValidationResultCache(IdentityServerBearerTokenAuthenticationOptions options, IClock clock, ICache cache) 
		{
		    if (clock == null) { throw new ArgumentNullException("clock"); }
		    if (options == null) { throw new ArgumentNullException("options"); }
		    if (cache == null) { throw new ArgumentNullException("cache"); }

			_options = options;
		    _cache = cache;
		    _clock = clock;
	    }
Ejemplo n.º 2
0
        public void Configure(IApplicationBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

            //app.Map("/action", application =>
            //{
            //    application.Use(async (context, next) =>
            //    {
            //        await context.Response.WriteAsync("Resource");
            //    });
            //});

            //app.UseOwin(pipe =>
            //{
            //    pipe(next =>
            //    {
            //        var builder = new AppBuilder();
            //        var provider = app.ApplicationServices.GetService<IDataProtectionProvider>();

            //        builder.Properties["security.DataProtectionProvider"] = new DataProtectionProviderDelegate(purposes =>
            //        {
            //            var dataProtection = provider.CreateProtector(string.Join(",", purposes));
            //            return new DataProtectionTuple(dataProtection.Protect, dataProtection.Unprotect);
            //        });

            //        builder.UseIdentityServerBearerTokenAuthentication(
            //            new IdentityServerBearerTokenAuthenticationOptions
            //            {
            //                Authority = "http://localhost:5000/core",
            //                ValidationMode = ValidationMode.ValidationEndpoint
            //            });

            //        return builder.Build<AppFunc>();
            //    });
            //});

            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

            var options = new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = "http://localhost:5000/core",
                ValidationMode = ValidationMode.ValidationEndpoint
            };

            app.UseAppBuilder(builder => { builder.UseIdentityServerBearerTokenAuthentication(options); }, "ResourceServer");

            app.Map("/action", application =>
            {
                application.Use(async (context, next) =>
                {
                    await context.Response.WriteAsync("Resource");
                });
            });
        }
		void Arrange(Action specifyExpectedCacheExpiry) {
			_cache = Mock.Of<ICache>();
			_clock = Mock.Of<IClock>(c => c.UtcNow == DateTimeOffset.Now);
			_options = new IdentityServerBearerTokenAuthenticationOptions
				{
					ValidationResultCacheDuration = TimeSpan.FromMinutes(CacheEvictsTokensAfterMinutes)
				};
			ExpiryClaimSaysTokenExpiresAt = _clock.UtcNow.AddMinutes(ExpiryClaimSaysTokenExpiresInMinutes);
			CacheExpiryEvictsTokenAt = _clock.UtcNow.Add(_options.ValidationResultCacheDuration);
			
			// setup claims to include expiry claim
			Claims = new[] {new Claim("bar","baz"), new Claim(ClaimTypes.Expiration,ExpiryClaimSaysTokenExpiresAt.ToEpochTime().ToString()) };

			specifyExpectedCacheExpiry();

			DebugToConsole(DateTime.Now, ExpiryClaimSaysTokenExpiresAt,  _options, CacheExpiryEvictsTokenAt, ExpectedCacheExpiry);
			Sut = new InMemoryValidationResultCache(_options, _clock, _cache);
		}
        public CachingDiscoveryIssuerSecurityTokenProvider(string discoveryEndpoint, IdentityServerBearerTokenAuthenticationOptions options)
        {
            var handler = options.BackchannelHttpHandler ?? new WebRequestHandler();

            if (options.BackchannelCertificateValidator != null)
            {
                // Set the cert validate callback
                var webRequestHandler = handler as WebRequestHandler;
                if (webRequestHandler == null)
                {
                    throw new InvalidOperationException("Invalid certificate validator");
                }
                webRequestHandler.ServerCertificateValidationCallback = options.BackchannelCertificateValidator.Validate;
            }

            _configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>(discoveryEndpoint, new HttpClient(handler));
            RetrieveMetadata();
        }
        public ValidationEndpointTokenProvider(IdentityServerBearerTokenAuthenticationOptions options)
        {
            var baseAddress = options.Authority.EnsureTrailingSlash();
            baseAddress += "connect/accesstokenvalidation";
            _tokenValidationEndpoint = baseAddress + "?token={0}";

            var handler = options.BackchannelHttpHandler ?? new WebRequestHandler();

            if (options.BackchannelCertificateValidator != null)
            {
                // Set the cert validate callback
                var webRequestHandler = handler as WebRequestHandler;
                if (webRequestHandler == null)
                {
                    throw new InvalidOperationException("Invalid certificate validator");
                }

                webRequestHandler.ServerCertificateValidationCallback = options.BackchannelCertificateValidator.Validate;
            }

            _client = new HttpClient(handler);
            _options = options;
        }
        /// <summary>
        /// Adds the access token validation middleware to the OWIN pipeline.
        /// </summary>
        /// <param name="app">The application.</param>
        /// <param name="options">The options.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">options</exception>
        public static IAppBuilder UseIdentityServerBearerTokenAuthentication(this IAppBuilder app, IdentityServerBearerTokenAuthenticationOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            if (options.ValidationMode == ValidationMode.Local)
            {
                app.UseLocalValidation(options);
            }
            else if (options.ValidationMode == ValidationMode.ValidationEndpoint)
            {
                app.UseValidationEndpoint(options);
            }

            if (options.RequiredScopes.Any())
            {
                app.Use<ScopeRequirementMiddleware>(options.RequiredScopes);
            }

            return app;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="InMemoryValidationResultCache"/> class.
        /// </summary>
        /// <param name="options">The options.</param>
	    public InMemoryValidationResultCache(IdentityServerBearerTokenAuthenticationOptions options) 
            : this(options, new Clock(), new Cache())
	    { }
		static void DebugToConsole(DateTime now, DateTimeOffset expiryClaimSaysTokenExpiresAt, IdentityServerBearerTokenAuthenticationOptions options, DateTimeOffset cacheExpiryEvictsTokenAt, DateTimeOffset expectedCacheExpiry) {
			Console.WriteLine("now: {0}", now);
			Console.WriteLine("expiry claim says token expires at: {0}", expiryClaimSaysTokenExpiresAt);
			Console.WriteLine("claims cache duration: {0}", options.ValidationResultCacheDuration);
			Console.WriteLine("cache expiry evicts token at: {0}", cacheExpiryEvictsTokenAt);
			Console.WriteLine("expected cache expiry: {0}", expectedCacheExpiry);
		}
        public void InvokingConstructor_WithNullIClock_ShouldError() 
		{
			var options = new IdentityServerBearerTokenAuthenticationOptions();			

			Assert.Throws<ArgumentNullException>(() => new InMemoryValidationResultCache(options, null, new Cache()));
		}
        public void InvokingConstructor_WithOptionsOnly_ShouldNotError() 
		{
			var options = new IdentityServerBearerTokenAuthenticationOptions();			

			new InMemoryValidationResultCache(options);
		}
        internal static void UseLocalValidation(this IAppBuilder app, IdentityServerBearerTokenAuthenticationOptions options)
        {
            JwtFormat tokenFormat = null;

            // use discovery document to fully configure middleware
            if (!string.IsNullOrEmpty(options.Authority))
            {
                var discoveryEndpoint = options.Authority.EnsureTrailingSlash();
                discoveryEndpoint += ".well-known/openid-configuration";

                var issuerProvider = new CachingDiscoveryIssuerSecurityTokenProvider(
                    discoveryEndpoint,
                    options);

                if (options.TokenValidationParameters != null)
                {
                    tokenFormat = new JwtFormat(options.TokenValidationParameters, issuerProvider);
                }
                else
                {
                    var valParams = new TokenValidationParameters
                    {
                        ValidAudience = issuerProvider.Audience,
                        NameClaimType = options.NameClaimType,
                        RoleClaimType = options.RoleClaimType
                    };

                    tokenFormat = new JwtFormat(valParams, issuerProvider);
                }
            }
            // use token validation parameters
            else if (options.TokenValidationParameters != null)
            {
                tokenFormat = new JwtFormat(options.TokenValidationParameters);
            }
            // use simplified manual configuration
            else
            {
                var valParams = new TokenValidationParameters
                {
                    ValidIssuer = options.IssuerName,
                    ValidAudience = options.IssuerName.EnsureTrailingSlash() + "resources",
                    IssuerSigningToken = new X509SecurityToken(options.IssuerCertificate),
                    NameClaimType = options.NameClaimType,
                    RoleClaimType = options.RoleClaimType
                };

                tokenFormat = new JwtFormat(valParams);
            }

            if (options.TokenHandler != null)
            {
                tokenFormat.TokenHandler = options.TokenHandler;
            }

            var bearerOptions = new OAuthBearerAuthenticationOptions
            {
                Provider = options.Provider,
                AccessTokenFormat = tokenFormat,
                AuthenticationMode = options.AuthenticationMode,
                AuthenticationType = options.AuthenticationType,
                Description = options.Description
            };

            app.UseOAuthBearerAuthentication(bearerOptions);
        }
        internal static void UseValidationEndpoint(this IAppBuilder app, IdentityServerBearerTokenAuthenticationOptions options)
        {
            if (options.EnableValidationResultCache)
            {
                if (options.ValidationResultCache == null)
                {
                    options.ValidationResultCache = new InMemoryValidationResultCache(options);
                }
            }

            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
            {
                AccessTokenProvider = new ValidationEndpointTokenProvider(options),
                Provider = options.Provider
            });
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="InMemoryValidationResultCache"/> class.
 /// </summary>
 /// <param name="options">The options.</param>
 public InMemoryValidationResultCache(IdentityServerBearerTokenAuthenticationOptions options)
     : this(options, new Clock(), new Cache())
 {
 }