Exemplo n.º 1
0
        public static TestServer CreateServer(OAuth2IntrospectionOptions options, bool addCaching = false)
        {
            return(new TestServer(new WebHostBuilder()
                                  .Configure(app =>
            {
                app.UseOAuth2IntrospectionAuthentication(options);

                app.Use((context, next) =>
                {
                    var user = context.User;

                    if (user.Identity.IsAuthenticated)
                    {
                        context.Response.StatusCode = 200;
                    }
                    else
                    {
                        context.Response.StatusCode = 401;
                    }

                    return Task.FromResult(0);
                });
            })
                                  .ConfigureServices(services =>
            {
                if (addCaching)
                {
                    services.AddDistributedMemoryCache();
                }

                services.AddAuthentication();
            })));
        }
        internal void ConfigureIntrospection(OAuth2IntrospectionOptions introspectionOptions)
        {
            if (String.IsNullOrWhiteSpace(ApiSecret))
            {
                return;
            }

            if (String.IsNullOrWhiteSpace(ApiName))
            {
                throw new ArgumentException("ApiName must be configured if ApiSecret is set.");
            }

            introspectionOptions.Authority       = Authority;
            introspectionOptions.ClientId        = ApiName;
            introspectionOptions.ClientSecret    = ApiSecret;
            introspectionOptions.NameClaimType   = NameClaimType;
            introspectionOptions.RoleClaimType   = RoleClaimType;
            introspectionOptions.TokenRetriever  = InternalTokenRetriever;
            introspectionOptions.SaveToken       = SaveToken;
            introspectionOptions.DiscoveryPolicy = IntrospectionDiscoveryPolicy;

            introspectionOptions.EnableCaching  = EnableCaching;
            introspectionOptions.CacheDuration  = CacheDuration;
            introspectionOptions.CacheKeyPrefix = CacheKeyPrefix;

            introspectionOptions.DiscoveryPolicy.RequireHttps = RequireHttpsMetadata;

            introspectionOptions.Events = new OAuth2IntrospectionEvents
            {
                OnAuthenticationFailed = e => OAuth2IntrospectionEvents.AuthenticationFailed(e),
                OnTokenValidated       = e => OAuth2IntrospectionEvents.OnTokenValidated(e),
            };
        }
Exemplo n.º 3
0
        private static OAuth2IntrospectionOptions ConfigureIntrospection(IdentityServerAuthenticationOptions options)
        {
            var introspectionOptions = new OAuth2IntrospectionOptions
            {
                AuthenticationScheme = options.AuthenticationScheme,
                Authority            = options.Authority,
                ScopeName            = options.ScopeName,
                ScopeSecret          = options.ScopeSecret,

                AutomaticAuthenticate = options.AutomaticAuthenticate,
                AutomaticChallenge    = options.AutomaticChallenge,

                NameClaimType = options.NameClaimType,
                RoleClaimType = options.RoleClaimType,

                TokenRetriever     = _tokenRetriever,
                SaveTokensAsClaims = options.SaveTokensAsClaims,

                DiscoveryTimeout     = options.BackChannelTimeouts,
                IntrospectionTimeout = options.BackChannelTimeouts
            };

            if (options.IntrospectionBackChannelHandler != null)
            {
                introspectionOptions.IntrospectionHttpHandler = options.IntrospectionBackChannelHandler;
            }
            if (options.IntrospectionDiscoveryHandler != null)
            {
                introspectionOptions.DiscoveryHttpHandler = options.IntrospectionDiscoveryHandler;
            }

            return(introspectionOptions);
        }
 public void Configure(string name, OAuth2IntrospectionOptions options)
 {
     if (name == _scheme + IdentityServerAuthenticationDefaults.IntrospectionAuthenticationScheme &&
         _identityServerOptions.SupportsIntrospection)
     {
         _identityServerOptions.ConfigureIntrospection(options);
     }
 }
 public ValueTask <IntrospectionRequest> GenerateRequestAsync(
     HttpRequest httpRequest,
     OAuth2IntrospectionOptions options,
     string token)
 {
     // Default introspection request
     return(new ValueTask <IntrospectionRequest>(new IntrospectionRequest
     {
         Token = token,
         TokenTypeHint = OidcConstants.TokenTypes.AccessToken,
         ClientId = options.ClientId,
         ClientSecret = options.ClientSecret
     }));
 }
        private static OAuth2IntrospectionOptions ConfigureIntrospection(IdentityServerAuthenticationOptions options)
        {
            if (String.IsNullOrWhiteSpace(options.ApiSecret))
            {
                return(null);
            }

            if (String.IsNullOrWhiteSpace(options.ApiName))
            {
                throw new ArgumentException("ApiName must be configured if ApiSecret is set.");
            }

            var introspectionOptions = new OAuth2IntrospectionOptions
            {
                AuthenticationScheme = options.AuthenticationScheme,
                Authority            = options.Authority,
                ClientId             = options.ApiName,
                ClientSecret         = options.ApiSecret,

                AutomaticAuthenticate = options.AutomaticAuthenticate,
                AutomaticChallenge    = options.AutomaticChallenge,

                NameClaimType = options.NameClaimType,
                RoleClaimType = options.RoleClaimType,

                TokenRetriever = _tokenRetriever,
                SaveToken      = options.SaveToken,

                EnableCaching = options.EnableCaching,
                CacheDuration = options.CacheDuration,

                DiscoveryTimeout     = options.BackChannelTimeouts,
                IntrospectionTimeout = options.BackChannelTimeouts
            };

            if (options.IntrospectionBackChannelHandler != null)
            {
                introspectionOptions.IntrospectionHttpHandler = options.IntrospectionBackChannelHandler;
            }
            if (options.IntrospectionDiscoveryHandler != null)
            {
                introspectionOptions.DiscoveryHttpHandler = options.IntrospectionDiscoveryHandler;
            }

            return(introspectionOptions);
        }
        public async Task Authority_Get_Introspection_Endpoint()
        {
            OAuth2IntrospectionOptions ops = null;
            var handler = new IntrospectionEndpointHandler(IntrospectionEndpointHandler.Behavior.Active);

            var client = PipelineFactory.CreateClient(options =>
            {
                options.Authority = "https://authority.com/";
                options.ClientId  = "scope";

                options.DiscoveryPolicy.RequireKeySet = false;
                ops = options;
            }, handler);

            client.SetBearerToken("token");
            await client.GetAsync("http://server/api");

            ops.IntrospectionEndpoint.Should().Be("https://authority.com/introspection_endpoint");
        }
        internal void ConfigureIntrospection(OAuth2IntrospectionOptions introspectionOptions)
        {
            if (String.IsNullOrWhiteSpace(ApiSecret))
            {
                return;
            }

            if (String.IsNullOrWhiteSpace(ApiName))
            {
                throw new ArgumentException("ApiName must be configured if ApiSecret is set.");
            }

            introspectionOptions.Authority       = Authority;
            introspectionOptions.ClientId        = ApiName;
            introspectionOptions.ClientSecret    = ApiSecret;
            introspectionOptions.NameClaimType   = NameClaimType;
            introspectionOptions.RoleClaimType   = RoleClaimType;
            introspectionOptions.TokenRetriever  = InternalTokenRetriever;
            introspectionOptions.SaveToken       = SaveToken;
            introspectionOptions.DiscoveryPolicy = IntrospectionDiscoveryPolicy;

            introspectionOptions.EnableCaching  = EnableCaching;
            introspectionOptions.CacheDuration  = CacheDuration;
            introspectionOptions.CacheKeyPrefix = CacheKeyPrefix;

            introspectionOptions.DiscoveryTimeout     = BackChannelTimeouts;
            introspectionOptions.IntrospectionTimeout = BackChannelTimeouts;

            introspectionOptions.DiscoveryPolicy.RequireHttps = RequireHttpsMetadata;

            if (IntrospectionBackChannelHandler != null)
            {
                introspectionOptions.IntrospectionHttpHandler = IntrospectionBackChannelHandler;
            }

            if (IntrospectionDiscoveryHandler != null)
            {
                introspectionOptions.DiscoveryHttpHandler = IntrospectionDiscoveryHandler;
            }
        }
Exemplo n.º 9
0
        public static TestServer CreateServer(OAuth2IntrospectionOptions options, bool addCaching = false)
        {
            return(new TestServer(new WebHostBuilder()
                                  .Configure(app =>
            {
                app.UseOAuth2IntrospectionAuthentication(options);

                app.Use(async(context, next) =>
                {
                    var user = context.User;

                    if (user.Identity.IsAuthenticated)
                    {
                        var responseObject = new Dictionary <string, string>
                        {
                            { "token", await context.Authentication.GetTokenAsync("access_token") }
                        };

                        var json = SimpleJson.SimpleJson.SerializeObject(responseObject);

                        context.Response.StatusCode = 200;
                        await context.Response.WriteAsync(json, Encoding.UTF8);
                    }
                    else
                    {
                        context.Response.StatusCode = 401;
                    }
                });
            })
                                  .ConfigureServices(services =>
            {
                if (addCaching)
                {
                    services.AddDistributedMemoryCache();
                }

                services.AddAuthentication();
            })));
        }
 public void Configure(OAuth2IntrospectionOptions options)
 {
 }
Exemplo n.º 11
0
 private void ConfigureIdentityServerAuthenticationOptions(OAuth2IntrospectionOptions options)
 {
     Configuration.GetSection("ApiAuthentication").Bind(options);
     options.ClientId     = Configuration.GetValue <string>("ApiAuthentication:ApiName");
     options.ClientSecret = Configuration.GetValue <string>("ApiAuthentication:ApiSecret");
Exemplo n.º 12
0
        public override void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <IUserStore <IdentityUser>, RawUserStore>();
            services.AddSingleton <IUserPasswordStore <IdentityUser>, RawUserStore>();
            services.AddSingleton <IPasswordValidator <IdentityUser>, RawUserStore>();
            services.AddSingleton <IUserClaimStore <IdentityUser>, RawUserStore>();
            services.AddSingleton <IPasswordHasher <IdentityUser>, RawUserStore>();
            services.AddSingleton <IProfileService, RawUserStore>();
            services.AddSingleton <IUserClaimsPrincipalFactory <IdentityUser>, RawClaimsFactory>();

            services.AddSingleton <RawRoleStore>();
            services.AddSingleton <IRoleStore <IdentityRole>, RawRoleStore>();
            services.AddIdentity <IdentityUser, IdentityRole>();

            // configure identity server with in-memory stores, keys, clients and scopes
            services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryPersistedGrants()
            .AddInMemoryIdentityResources(this.config.GetIdentityResources())
            .AddInMemoryApiResources(config.GetApiResources())
            .AddInMemoryClients(config.GetClients())
            .AddAspNetIdentity <IdentityUser>()
            .AddProfileServiceCustom();

            if (config.Mode == OAuthMode.External)
            {
                OAuth2IntrospectionOptions options = new OAuth2IntrospectionOptions
                {
                    //base - address of your identityserver
                    Authority    = config.Authority,
                    ClientSecret = config.ClientSecret,
                    ClientId     = config.ClientId,
                    BasicAuthenticationHeaderStyle = IdentityModel.Client.BasicAuthenticationHeaderStyle.Rfc2617
                };
                if (!string.IsNullOrWhiteSpace(config.IntrospectionEndpoint))
                {
                    options.IntrospectionEndpoint = config.IntrospectionEndpoint;
                }
                options.TokenTypeHint = "Bearer";
                if (!string.IsNullOrWhiteSpace(config.TokenTypeHint))
                {
                    options.TokenTypeHint = config.TokenTypeHint;
                }

                options.Validate();

                services.AddAuthentication(OAuth2IntrospectionDefaults.AuthenticationScheme)
                .AddOAuth2Introspection(x =>
                {
                    x = options;
                });
            }
            else
            {
                services.AddAuthentication(OAuth2IntrospectionDefaults.AuthenticationScheme)
                //.AddOAuth2Introspection( x => {
                //    x = options;
                //});
                .AddIdentityServerAuthentication("Bearer", options =>
                {
                    options.Authority            = config.Authority;
                    options.ApiName              = config.ApiResource;
                    options.ApiSecret            = config.ClientSecret;
                    options.RequireHttpsMetadata = false;
                    options.SaveToken            = true;
                    options.NameClaimType        = ClaimTypes.NameIdentifier;
                });
            }
        }
Exemplo n.º 13
0
        public override void ConfigureServices(IServiceCollection services)
        {
            IdentityModelEventSource.ShowPII = true;
            services.AddSingleton <IUserStore <IdentityUser>, RawUserStore>();
            services.AddSingleton <IUserPasswordStore <IdentityUser>, RawUserStore>();
            services.AddSingleton <IPasswordValidator <IdentityUser>, RawUserStore>();
            services.AddSingleton <IUserClaimStore <IdentityUser>, RawUserStore>();
            services.AddSingleton <IPasswordHasher <IdentityUser>, RawUserStore>();
            services.AddSingleton <IProfileService, RawUserStore>();
            services.AddSingleton <IUserClaimsPrincipalFactory <IdentityUser>, RawClaimsFactory>();

            services.AddSingleton <RawRoleStore>();
            services.AddSingleton <IRoleStore <IdentityRole>, RawRoleStore>();
            services.AddIdentity <IdentityUser, IdentityRole>();

            // configure identity server with in-memory stores, keys, clients and scopes
            services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryPersistedGrants()
            .AddInMemoryIdentityResources(this.config.GetIdentityResources())
            .AddInMemoryApiResources(config.GetApiResources())
            .AddInMemoryClients(config.GetClients())
            .AddAspNetIdentity <IdentityUser>()
            .AddProfileServiceCustom();

            if (config.Mode == OAuthMode.External)
            {
                OAuth2IntrospectionOptions options = new OAuth2IntrospectionOptions
                {
                    //base - address of your identityserver
                    Authority    = config.Authority,
                    ClientSecret = config.ClientSecret,
                    ClientId     = config.ClientId,
                    BasicAuthenticationHeaderStyle = IdentityModel.Client.BasicAuthenticationHeaderStyle.Rfc2617
                };
                if (!string.IsNullOrWhiteSpace(config.IntrospectionEndpoint))
                {
                    options.IntrospectionEndpoint = config.IntrospectionEndpoint;
                }
                options.TokenTypeHint = "Bearer";
                if (!string.IsNullOrWhiteSpace(config.TokenTypeHint))
                {
                    options.TokenTypeHint = config.TokenTypeHint;
                }

                options.Validate();

                services.AddAuthentication(OAuth2IntrospectionDefaults.AuthenticationScheme)
                .AddOAuth2Introspection(x =>
                {
                    x = options;
                });
            }
            else
            {
                services
                .AddAuthentication((options) =>
                {
                    options.DefaultScheme          = "Bearer";
                    options.DefaultChallengeScheme = "Bearer";
                    //options.AddScheme("ApiKey", (x) => { x.HandlerType = typeof(RawLocalAccessTokenValidationHandler); });
                })
                .AddJwtBearer("Bearer" + IdentityServerAuthenticationDefaults.AuthenticationScheme, (options) =>
                {
                    options.RequireHttpsMetadata      = false;
                    options.SaveToken                 = true;
                    options.IncludeErrorDetails       = true;
                    options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                    {
                        RoleClaimType = ClaimTypes.Role,
                        NameClaimType = ClaimTypes.NameIdentifier
                    };
                    //options.Audience = IdentityServer4.IdentityServerConstants.LocalIdentityProvider;
                    //options.Authority = IdentityServer4.IdentityServerConstants.LocalIdentityProvider;
                    options.Validate();
                })
                .AddScheme <RawIdentityServerAuthenticationOptions, RawLocalAccessTokenValidationHandler>("Bearer", (o) =>
                {
                    o.AdminApiKey = this.config.AdminApiKey;
                    o.ApiKey      = this.config.ApiKey;
                })
                .AddScheme <RawIdentityServerAuthenticationOptions, RawLocalAccessTokenValidationHandler>("ApiKey", (o) =>
                {
                    o.AdminApiKey = this.config.AdminApiKey;
                    o.ApiKey      = this.config.ApiKey;
                });
            }
        }
Exemplo n.º 14
0
 public static HttpMessageHandler CreateHandler(OAuth2IntrospectionOptions options, bool addCaching = false)
 {
     return(CreateServer(options, addCaching).CreateHandler());
 }
Exemplo n.º 15
0
 public static HttpClient CreateClient(OAuth2IntrospectionOptions options, bool addCaching = false)
 {
     return(CreateServer(options, addCaching).CreateClient());
 }