本文整理汇总了C#中IApplicationBuilder.UseOAuthValidation方法的典型用法代码示例。如果您正苦于以下问题:C# IApplicationBuilder.UseOAuthValidation方法的具体用法?C# IApplicationBuilder.UseOAuthValidation怎么用?C# IApplicationBuilder.UseOAuthValidation使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IApplicationBuilder
的用法示例。
在下文中一共展示了IApplicationBuilder.UseOAuthValidation方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Configure
public void Configure(IApplicationBuilder app) {
app.UseDefaultFiles();
app.UseStaticFiles();
// Add a new middleware validating access tokens.
app.UseOAuthValidation(options => {
options.Events = new OAuthValidationEvents {
// Note: for SignalR connections, the default Authorization header does not work,
// because the WebSockets JS API doesn't allow setting custom parameters.
// To work around this limitation, the access token is retrieved from the query string.
OnRetrieveToken = context => {
context.Token = context.Request.Query["access_token"];
return Task.FromResult(0);
}
};
});
app.UseSignalR<SimpleConnection>("/signalr");
// Add a new middleware issuing access tokens.
app.UseOpenIdConnectServer(options => {
options.Provider = new AuthenticationProvider();
// Enable the token endpoint.
options.TokenEndpointPath = "/connect/token";
options.AllowInsecureHttp = true;
});
}
示例2: Configure
public void Configure(IApplicationBuilder app) {
// To test this sample with Postman, use the following settings:
//
// * Authorization URL: http://localhost:6500/connect/authorize
// * Access token URL: http://localhost:6500/connect/token
// * Client ID: postman
// * Client secret: [blank] (not used with public clients)
// * Scope: openid email profile roles
// * Grant type: authorization code
// * Request access token locally: yes
app.UseDeveloperExceptionPage();
app.UseStaticFiles();
app.UseOAuthValidation();
app.UseOpenIdConnectServer(options => {
options.Provider = new AuthorizationProvider();
// Enable the authorization and token endpoints.
options.AuthorizationEndpointPath = "/connect/authorize";
options.TokenEndpointPath = "/connect/token";
options.AllowInsecureHttp = true;
});
app.UseMvc();
app.UseWelcomePage();
}
示例3: Configure
public void Configure(IApplicationBuilder app) {
app.UseDefaultFiles();
app.UseStaticFiles();
// Add a new middleware validating access tokens.
app.UseOAuthValidation(options => {
options.Events = new OAuthValidationEvents {
// Note: for SignalR connections, the default Authorization header does not work,
// because the WebSockets JS API doesn't allow setting custom parameters.
// To work around this limitation, the access token is retrieved from the query string.
OnRetrieveToken = context => {
context.Token = context.Request.Query["access_token"];
return Task.FromResult(0);
}
};
});
app.UseSignalR<SimpleConnection>("/signalr");
// Add a new middleware issuing access tokens.
app.UseOpenIdConnectServer(options => {
options.Provider = new AuthorizationProvider();
// Enable the token endpoint.
options.TokenEndpointPath = "/connect/token";
options.AllowInsecureHttp = true;
// Register a new ephemeral key, that is discarded when the application
// shuts down. Tokens signed using this key are automatically invalidated.
// This method should only be used during development.
options.SigningCredentials.AddEphemeralKey();
// On production, using a X.509 certificate stored in the machine store is recommended.
// You can generate a self-signed certificate using Pluralsight's self-cert utility:
// https://s3.amazonaws.com/pluralsight-free/keith-brown/samples/SelfCert.zip
//
// options.SigningCredentials.AddCertificate("7D2A741FE34CC2C7369237A5F2078988E17A6A75");
});
}
示例4: Configure
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseOAuthValidation();
app.UseCors(p => p.AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials());
app.UseOpenIdConnectServer(options => {
// Create your own authorization provider by subclassing
// the OpenIdConnectServerProvider base class.
options.Provider = new AuthorizationProvider();
options.IdentityTokenLifetime = TimeSpan.FromDays(1460);
options.AccessTokenLifetime = TimeSpan.FromDays(1460);
// Enable the authorization and token endpoints.
options.AuthorizationEndpointPath = "/api/authorize";
options.TokenEndpointPath = "/api/token";
// During development, you can set AllowInsecureHttp
// to true to disable the HTTPS requirement.
//if (env.IsDevelopment())
options.AllowInsecureHttp = true;
var jwtSigningCert = new X509Certificate2(Path.Combine(env.ContentRootPath,"AuthSample.pfx"), Configuration["PfxPw"]);
options.SigningCredentials.AddCertificate(jwtSigningCert);
// Note: uncomment this line to issue JWT tokens.
// options.AccessTokenHandler = new JwtSecurityTokenHandler();
});
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
//if (env.IsDevelopment() || env.IsStaging())
// DbContextExtensions.Seed(app);
app.UseApplicationInsightsRequestTelemetry();
app.UseApplicationInsightsExceptionTelemetry();
app.UseMvc();
}
示例5: Configure
/// <summary>
/// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
/// </summary>
/// <param name="app"></param>
/// <param name="env"></param>
/// <param name="loggerFactory"></param>
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions()
{
HotModuleReplacement = true
});
app.UseSwagger(documentFilter: (swaggerDoc, httpRequest) =>
{
swaggerDoc.Host = httpRequest.Host.Value;
});
app.UseSwaggerUi(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "V1 Docs");
c.ConfigureOAuth2("test-client-id123", "test-client-secr43et", "test-rea32lm", "test-a11pp");
}
);
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseCors("MyPolicy");
//app.Use(async (context, next) =>
//{
// await next();
// if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
// {
// context.Request.Path = "/index.html"; // Put your Angular root page here
// await next();
// }
//});
//var angularRoutes = new[] {
// "/api",
// "/connect"
// };
//app.Use(async (context, next) =>
//{
// if (context.Request.Path.HasValue && null == angularRoutes.FirstOrDefault(
// (ar) => context.Request.Path.Value.StartsWith(ar, StringComparison.OrdinalIgnoreCase)))
// {
// context.Request.Path = new PathString("/");
// }
// await next();
//});
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseIdentity();
app.UseOAuthValidation();
app.UseOpenIddict();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new {controller = "Home", action = "Index"});
});
//builder =>
//{
//builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin();
//});
}
示例6: Configure
public void Configure(IApplicationBuilder app, IHostingEnvironment appEnv, ILoggerFactory loggerFactory)
{
var path = appEnv.ContentRootPath + Configuration["AppSettings:Logs"];
//app.UseIISPlatformHandler();
//loggerFactory.AddProvider(new DivineLoggerProvider(new FileStorage(path)));
//.AddSerilog(GetLogConfiguration(appEnv.ApplicationBasePath).CreateLogger());
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
// if (appEnv.IsDevelopment())
// {
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
//}
//else
//{
// app.UseExceptionHandler("/Home/Error");
// // For more details on creating database during deployment see http://go.microsoft.com/fwlink/?LinkID=615859
//}
app.UseCors("AllowAll");
app.UseStaticFiles();
app.UseSession();
app.UseIdentity();
// app.UseCookieAuthentication(new CookieAuthenticationOptions { LoginPath = "/Account/Login", LogoutPath = "/Account/Logout" });
app.UseOAuthValidation(); // enabled auth through bearer tokens
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
//seeder.Initialize(app.ApplicationServices);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
app.UseOpenIddict();
app.UseMvc();
}
示例7: Configure
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory,
ImperaContext dbContext,
DbSeed dbSeed)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
// Enable Cors
app.UseCors(b => b.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().DisallowCredentials().Build());
// Auth
app.UseIdentity();
//app.UseFacebookAuthentication(new FacebookOptions
//{
// ClientId = Configuration["Authentication:Facebook:ClientId"],
// AppId = Configuration["Authentication:Facebook:AppId"],
// AppSecret = Configuration["Authentication:Facebook:AppSecret"]
//});
app.UseOAuthValidation(options => {
options.Events = new AspNet.Security.OAuth.Validation.OAuthValidationEvents
{
// Note: for SignalR connections, the default Authorization header does not work,
// because the WebSockets JS API doesn't allow setting custom parameters.
// To work around this limitation, the access token is retrieved from the query string.
OnRetrieveToken = context => {
context.Token = context.Request.Query["bearer_token"];
return Task.FromResult(0);
}
};
});
app.UseOpenIddict();
app.UseMvc();
app.UseWebSockets();
app.UseSignalR();
app.UseSwagger();
app.UseSwaggerUi();
// Initialize database
if (env.IsDevelopment())
{
// Always recreate in development
//dbContext.Database.EnsureDeleted();
dbContext.Database.EnsureCreated();
}
else
{
dbContext.Database.Migrate();
}
dbSeed.Seed(dbContext).Wait();
AutoMapperConfig.Configure();
// Hangfire
app.UseHangfireServer(new BackgroundJobServerOptions
{
Queues = new[] { JobQueues.Critical, JobQueues.Normal },
});
app.UseHangfireDashboard();
Hangfire.Common.JobHelper.SetSerializerSettings(new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All });
// Configure Impera background jobs
JobConfig.Configure();
}
示例8: Configure
/// <summary>
/// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
/// </summary>
/// <param name="app"></param>
/// <param name="env"></param>
/// <param name="loggerFactory"></param>
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddNLog();
try
{
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
.CreateScope())
{
serviceScope.ServiceProvider.GetService<BddContext>()
.Database.Migrate();
serviceScope.ServiceProvider.GetService<ApplicationDbContext>()
.Database.Migrate();
serviceScope.ServiceProvider.GetService<BddContext>().EnsureSeedData();
}
}
catch { }
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
app.UseIdentity();
app.UseOAuthValidation();
app.UseOpenIddict();
app.UseGoogleAuthentication(new GoogleOptions()
{
ClientId = Configuration["GOOGLE_CLIENT_ID"],
ClientSecret = Configuration["GOOGLE_CLIENT_SECRET"]
});
app.UseFacebookAuthentication(new FacebookOptions()
{
AppId = Configuration["FACEBOOK_APP_ID"],
AppSecret = Configuration["FACEBOOK_SECRET_ID"]
});
app.UseMiddleware<WebAPILoggerMiddleware>();
app.UseMvc(routes =>
{
routes.MapRoute("journee",
template: "Journee/Index/{equipe}/{idJournee}", defaults: new { controller = "Journee", action="Index", equipe="equipe1", idJournee = 1});
routes.MapRoute("actu",
template: "Journee/Detail/{url}", defaults: new { controller = "Journee", action = "Index", equipe = "equipe1", idJournee = 1 });
routes.MapRoute(
name: "default",
template: "{controller=Actu}/{action=Index}/{id?}");
});
app.UseSwagger();
app.UseSwaggerUi();
app.AddNLogWeb();
using (var context = new ApplicationDbContext(app.ApplicationServices.GetRequiredService<DbContextOptions<ApplicationDbContext>>()))
{
context.Database.EnsureCreated();
var applications = context.Set<OpenIddictApplication>();
// Add Mvc.Client to the known applications.
if (!applications.Any())
{
// Note: when using the introspection middleware, your resource server
// MUST be registered as an OAuth2 client and have valid credentials.
//
// context.Applications.Add(new OpenIddictApplication {
// Id = "resource_server",
// DisplayName = "Main resource server",
// Secret = Crypto.HashPassword("secret_secret_secret"),
// Type = OpenIddictConstants.ClientTypes.Confidential
// });
applications.Add(new OpenIddictApplication
{
ClientId = "xamarin-auth",
ClientSecret = Crypto.HashPassword(Configuration["OPENIDDICT_CLIENT_SECRET"]),
DisplayName = "HOFC",
LogoutRedirectUri = "https://local.webhofc.fr/",
RedirectUri = "urn:ietf:wg:oauth:2.0:oob",
//.........这里部分代码省略.........
示例9: Configure
public void Configure(IApplicationBuilder app)
{
var factory = app.ApplicationServices.GetRequiredService<ILoggerFactory>();
factory.AddConsole();
factory.AddDebug();
app.UseIISPlatformHandler(options => {
options.FlowWindowsAuthentication = false;
});
app.UseOverrideHeaders(options => {
options.ForwardedOptions = ForwardedHeaders.All;
});
app.UseStaticFiles();
// Add a middleware used to validate access
// tokens and protect the API endpoints.
app.UseOAuthValidation();
// Alternatively, you can also use the introspection middleware.
// Using it is recommended if your resource server is in a
// different application/separated from the authorization server.
//
// app.UseOAuthIntrospection(options => {
// options.AutomaticAuthenticate = true;
// options.AutomaticChallenge = true;
// options.Authority = "http://localhost:54540/";
// options.Audience = "resource_server";
// options.ClientId = "resource_server";
// options.ClientSecret = "875sqd4s5d748z78z7ds1ff8zz8814ff88ed8ea4z4zzd";
// });
app.UseIdentity();
//var settings = app.ApplicationServices.GetService<AppSettings>();
//app.UseGoogleAuthentication(new GoogleOptions() {
// ClientId = settings.OAuth.Google.ClientId,
// ClientSecret = settings.OAuth.Google.ClientSecret
//});
//app.UseTwitterAuthentication(new TwitterOptions()
//{
// ConsumerKey = settings.OAuth.Twitter.ClientId,
// ConsumerSecret = settings.OAuth.Twitter.ClientSecret
//});
// Note: OpenIddict must be added after
// ASP.NET Identity and the external providers.
app.UseOpenIddict(options =>
{
// You can customize the default Content Security Policy (CSP) by calling UseNWebsec explicitly.
// This can be useful to allow your HTML views to reference remote scripts/images/styles.
options.UseNWebsec(directives =>
{
directives.DefaultSources(directive => directive.Self())
.ImageSources(directive => directive.Self().CustomSources("*"))
.ScriptSources(directive => directive
.Self()
.UnsafeInline()
.CustomSources("https://my.custom.url"))
.StyleSources(directive => directive.Self().UnsafeInline());
});
});
app.UseMvcWithDefaultRoute();
// CreateClients(app);
}
示例10: Configure
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, ILoggerFactory factory) {
factory.AddConsole();
factory.AddDebug();
app.UseIISPlatformHandler();
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.All
});
app.UseDeveloperExceptionPage();
app.UseStaticFiles();
// Add a middleware used to validate access
// tokens and protect the API endpoints.
app.UseOAuthValidation();
// Alternatively, you can also use the introspection middleware.
// Using it is recommended if your resource server is in a
// different application/separated from the authorization server.
//
// app.UseOAuthIntrospection(options => {
// options.AutomaticAuthenticate = true;
// options.AutomaticChallenge = true;
// options.Authority = "http://localhost:54540/";
// options.Audience = "resource_server";
// options.ClientId = "resource_server";
// options.ClientSecret = "875sqd4s5d748z78z7ds1ff8zz8814ff88ed8ea4z4zzd";
// });
app.UseIdentity();
// Note: OpenIddict must be added after
// ASP.NET Identity and the external providers.
app.UseOpenIddict(options =>
{
// You can customize the default Content Security Policy (CSP) by calling UseNWebsec explicitly.
// This can be useful to allow your HTML views to reference remote scripts/images/styles.
options.UseNWebsec(directives =>
{
directives.ChildSources(directive => directive.Self())
.DefaultSources(directive => directive.Self())
.ImageSources(directive => directive.Self().CustomSources("*"))
.FontSources(directive => directive.Self().CustomSources("data:"))
.ScriptSources(directive => directive
.Self()
.UnsafeEval()
.UnsafeInline()
.CustomSources("https://my.custom.url"))
.StyleSources(directive => directive.Self().UnsafeInline().CustomSources("data:"));
});
});
// To configure external authentication please see http://go.microsoft.com/fwlink/?LinkID=532715
app.UseMvcWithDefaultRoute();
//app.UseSwaggerGen();
//app.UseSwaggerUi();
using (var context = app.ApplicationServices.GetRequiredService<ApplicationDbContext>())
{
context.Database.EnsureCreated();
// Add Mvc.Client to the known applications.
if (!context.Applications.Any())
{
// Note: when using the introspection middleware, your resource server
// MUST be registered as an OAuth2 client and have valid credentials.
//
// context.Applications.Add(new Application {
// Id = "resource_server",
// DisplayName = "Main resource server",
// Secret = "875sqd4s5d748z78z7ds1ff8zz8814ff88ed8ea4z4zzd"
// });
var hasher = new PasswordHasher<Application>();
context.Applications.Add(new Application
{
Id = "myClient",
DisplayName = "My client application",
RedirectUri = "http://localhost:53507/signin-oidc",
LogoutRedirectUri = "http://localhost:53507/",
Secret = Crypto.HashPassword("secret_secret_secret"),
Type = OpenIddictConstants.ApplicationTypes.Confidential
});
// To test this sample with Postman, use the following settings:
//
// * Authorization URL: http://localhost:54540/connect/authorize
// * Access token URL: http://localhost:54540/connect/token
// * Client ID: postman
// * Client secret: [blank] (not used with public clients)
// * Scope: openid email profile roles
// * Grant type: authorization code
// * Request access token locally: yes
context.Applications.Add(new Application
{
//.........这里部分代码省略.........