本文整理汇总了C#中IApplicationBuilder.UseJwtBearerAuthentication方法的典型用法代码示例。如果您正苦于以下问题:C# IApplicationBuilder.UseJwtBearerAuthentication方法的具体用法?C# IApplicationBuilder.UseJwtBearerAuthentication怎么用?C# IApplicationBuilder.UseJwtBearerAuthentication使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IApplicationBuilder
的用法示例。
在下文中一共展示了IApplicationBuilder.UseJwtBearerAuthentication方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Configure
public void Configure(IApplicationBuilder app)
{
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap = new Dictionary<string, string>();
// IdentityServer3 hardcodes the audience as '{host-address}/resources'.
// It is suggested to do the validation on scopes.
// That's why audience validation is disabled with 'ValidateAudience = false' below.
app.UseJwtBearerAuthentication(options =>
{
options.Authority = "http://localhost:44300/";
options.TokenValidationParameters.ValidateAudience = false;
options.AutomaticAuthentication = true;
if (_hostingEnv.IsDevelopment())
{
options.ConfigurationManager = new ConfigurationManager<OpenIdConnectConfiguration>(
metadataAddress: $"{options.Authority}.well-known/openid-configuration",
configRetriever: new OpenIdConnectConfigurationRetriever(),
docRetriever: new HttpDocumentRetriever { RequireHttps = false }
);
}
});
app.UseCors(policy => policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin())
.UseMiddleware<AuthenticatedUserLoggingMiddleware>()
.UseMvc();
}
示例2: Configure
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.MinimumLevel = LogLevel.Information;
loggerFactory.AddConsole();
loggerFactory.AddDebug();
app.UseIISPlatformHandler();
app.UseExceptionHandler("/Home/Error");
app.UseCors("corsGlobalPolicy");
app.UseStaticFiles();
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap = new Dictionary<string, string>();
app.UseJwtBearerAuthentication(options =>
{
options.Authority = "https://localhost:44345";
options.Audience = "https://localhost:44345/resources";
options.AutomaticAuthenticate = true;
});
app.UseMiddleware<RequiredScopesMiddleware>(new List<string> { "dataEventRecords" });
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
示例3: 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.UseIISPlatformHandler();
ApplicationConfiguration.SetContext("Elders.Pandora.Api");
foreach (var directory in new[] { Folders.Main, Folders.Users, Folders.Projects })
{
if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);
}
// Configure the HTTP request pipeline.
app.UseStaticFiles();
app.UseJwtBearerAuthentication(new JwtBearerOptions()
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
TokenValidationParameters = GoogleTokenValidationParameters.GetParameters()
});
app.UseClaimsTransformation(new ClaimsTransformationOptions() { Transformer = new ClaimsTransformer() });
// Add MVC to the request pipeline.
app.UseMvc();
}
示例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)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("CorsPolicy");
app.UseDefaultFiles();
app.UseStaticFiles();
var tokenValidationParameters = CreateTokenValidationParameters();
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
TokenValidationParameters = tokenValidationParameters
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "Default",
template: "api/{controller}/{action}/{id?}"
);
});
}
示例5: 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)
{
loggerFactory.AddConsole();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
var jwtBearerOptions = new JwtBearerOptions
{
AuthenticationScheme = JwtBearerDefaults.AuthenticationScheme,
AutomaticAuthenticate = true
};
jwtBearerOptions.SecurityTokenValidators.Clear();
jwtBearerOptions.SecurityTokenValidators.Add(new TicketDataFormatTokenValidator());
app.UseJwtBearerAuthentication(jwtBearerOptions);
app.UseMvc(
routes =>
{
routes.MapRoute(
"WebApi",
"api/{controller}/{action}/{id?}",
new { action = "Get" }
);
}
);
}
示例6: Configure
public void Configure(IApplicationBuilder app, IHostingEnvironment environment, ILoggerFactory factory) {
factory.AddConsole();
factory.AddDebug();
app.UseIISPlatformHandler();
if (environment.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
app.UseDefaultFiles();
app.UseStaticFiles();
// Add a new middleware validating access tokens.
app.UseJwtBearerAuthentication(options => {
// Automatic authentication must be enabled
// for SignalR to receive the access token.
options.AutomaticAuthenticate = true;
// Automatically disable the HTTPS requirement for development scenarios.
options.RequireHttpsMetadata = !environment.IsDevelopment();
// Note: the audience must correspond to the address of the SignalR server.
options.Audience = "http://localhost:5000/";
// Note: the authority must match the address of the identity server.
options.Authority = "http://localhost:5000/";
options.Events = new JwtBearerEvents {
// 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.
OnReceivingToken = context => {
// Note: when the token is missing from the query string,
// context.Token is null and the JWT bearer middleware will
// automatically try to retrieve it from the Authorization header.
context.Token = context.Request.Query["access_token"];
return Task.FromResult(0);
}
};
});
app.UseWebSockets();
app.UseSignalR<SimpleConnection>("/signalr");
// Add a new middleware issuing access tokens.
app.UseOpenIdConnectServer(options => {
options.Provider = new AuthenticationProvider();
});
}
示例7: Configure
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
app.UseStaticFiles();
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
TokenValidationParameters = new TokenValidationParameters()
{
IssuerSigningKey = key,
ValidAudience = tokenOptions.Audience,
ValidIssuer = tokenOptions.Issuer,
// When receiving a token, check that we've signed it.
ValidateIssuerSigningKey = true,
// When receiving a token, check that it is still valid.
ValidateLifetime = true,
// This defines the maximum allowable clock skew - i.e. provides a tolerance on the
// token expiry time when validating the lifetime. As we're creating the tokens locally
// and validating them on the same machines which should have synchronised
// time, this can be set to zero. Where external tokens are used, some leeway here
// could be useful.
ClockSkew = TimeSpan.Zero
}
});
app.UseIdentity();
app.UseCors(
builder => builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
app.UseMvc(routes =>
{
routes.MapRoute(
name: "api",
template: "api/{controller}/{action=GetAll}/{id?}");
});
var logger = loggerFactory.CreateLogger("Startup");
logger.LogInformation("Application initialized");
logger.LogInformation($"Environment: {_hostingEnv.EnvironmentName}");
logger.LogInformation("Database name: " + _configuration["Data:DefaultConnection:Database"]);
app.ApplicationServices.GetService<IInitializeDataManager>().Initialize();
}
示例8: Configure
public void Configure(IApplicationBuilder app)
{
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap = new Dictionary<string, string>();
app.UseJwtBearerAuthentication(options =>
{
options.Authority = "https://localhost:44300";
options.Audience = "https://localhost:44300/resources";
options.AutomaticAuthentication = true;
});
app.UseMiddleware<RequiredScopesMiddleware>(new List<string> { "api1" });
app.UseMvcWithDefaultRoute();
}
示例9: Configure
// Configure is called after ConfigureServices is called.
public void Configure(IApplicationBuilder app,ILoggerFactory loggerFactory, IHostingEnvironment env,IRuntimeEnvironment runtimeEnv,IConnectionManager connectionManager)
{
app.UseStaticFiles();
app.UseIISPlatformHandler();
app.UseCors("OpenBookAPI");
app.UseSwagger();
app.UseSwaggerUi();
app.UseSignalR();
var hubContext = connectionManager.GetHubContext<OpenBookAPI.SignalR.Hubs.LogHub>();
app.UseJwtBearerAuthentication(options =>
{
options.Audience = Configuration["Auth:ClientId"];
options.Authority = Configuration["Auth:Domain"];
options.AuthenticationScheme = "Automatic";
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateLifetime = true
};
});
var localLogger = new LoggerConfiguration()
.WriteTo.Trace()
.WriteTo.Console().CreateLogger();
var signalRlogger = new LoggerConfiguration()
.WriteTo.Sink(new SignalRSink(hubContext, 10))
.MinimumLevel.Warning()
.CreateLogger();
var azureLogger = new LoggerConfiguration()
.WriteTo.AzureDocumentDB(new System.Uri("https://openbook.documents.azure.com:443/"), "j4Hzifc5HL6z4uNt152t6ECrI5J7peGpSJDlwfkEzn5Vs94pAxf71N3sw3iQS6YneXC0CvxA+MdQjP/GKVbo6A==")
.MinimumLevel.Warning()
.CreateLogger();
if (runtimeEnv.OperatingSystem.Equals("Windows", StringComparison.OrdinalIgnoreCase))
{
loggerFactory.AddSerilog(azureLogger);
}
if (env.IsDevelopment())
{
loggerFactory.AddSerilog(localLogger);
}
loggerFactory.AddSerilog(signalRlogger);
//should go at the end
app.UseMvc();
}
示例10: 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)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseJwtBearerAuthentication(new JwtBearerOptions()
{
Audience = "http://localhost:54710/resources",
TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = "http://localhost:54710",
ValidAudience = "http://localhost:54710/resources",
IssuerSigningKey = new RsaSecurityKey(Newtonsoft.Json.JsonConvert.DeserializeObject<RSAParameters>("{\"D\":null,\"DP\":null,\"DQ\":null,\"Exponent\":\"AQAB\",\"InverseQ\":null,\"Modulus\":\"439rhEc+WB6j/ds2m3Kqfm9+aYQsM7fzOjDUWn5r/7b3lyOOy0MX+24h+kwXCQqne2MAwByxt2yXQwEk5/HR8o2PCTbgeb9OhvC1Biq2E5UAzpBK9F06H/q+zwkeVJyHFUn4d96HfevzzC/rrZgTiFhuD3TYxtd0c5JNR3gbmd+PvAwzzzdrgSwnGmyHVJk6GHmw5ilaeupBn3w8ITleQy8jh//jO0RxQaXnEY6LlMYFC7lZx1gNrEgxw0gIW8UuWebV6p1SU9A4nP79PTQcDITXWEyiDWJtIhNRJqLviCB4EnwJQ/IgewEBU/yNYrOaQqPrLiMmNS5VfqfrczYOqQ==\",\"P\":null,\"Q\":null}"))
}
});
app.UseMvc();
}
示例11: 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)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseJwtBearerAuthentication(new JwtBearerOptions{
AutomaticAuthenticate = true,
Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"],
Audience = Configuration["Authentication:AzureAd:Audience"]
});
app.UseCors(builder =>
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseMvc();
}
示例12: 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)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseIISPlatformHandler();
app.UseStaticFiles();
app.UseJwtBearerAuthentication(options =>
{
options.AutomaticAuthenticate = true;
options.AutomaticChallenge = true;
options.Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"];
options.Audience = Configuration["Authentication:AzureAd:TenantId"];
});
app.UseMvc();
}
示例13: Configure
// Configure is called after ConfigureServices is called.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// Configure the HTTP request pipeline.
//app.UseStaticFiles();
app.UseDeveloperExceptionPage();
app.UseJwtBearerAuthentication(options =>
{
options.AutomaticAuthentication = true;
options.SecurityTokenValidators.Add(new CustomJwtSecurityTokenHandler());
options.TokenValidationParameters.ValidateLifetime = false;
});
// Add MVC to the request pipeline.
app.UseMvc();
// Add the following route for porting Web API 2 controllers.
// routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
}
示例14: Configure
public void Configure(IApplicationBuilder app)
{
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
Authority = "https://demo.identityserver.io",
Audience = "https://demo.identityserver.io/resources",
AutomaticAuthenticate = true,
TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name",
RoleClaimType = "role"
}
});
app.UseMvc();
}
示例15: Configure
// Configure is called after ConfigureServices is called.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerfactory)
{
loggerfactory.AddConsole();
var logger = loggerfactory.CreateLogger("Auth0");
var settings = app.ApplicationServices.GetService<IOptions<Auth0Settings>>();
app.UseJwtBearerAuthentication(options =>
{
options.Audience = settings.Value.ClientId;
options.Authority = $"https://{settings.Value.Domain}";
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
logger.LogError("Authentication failed.", context.Exception);
return Task.FromResult(0);
},
OnValidatedToken = context =>
{
var claimsIdentity = context.AuthenticationTicket.Principal.Identity as ClaimsIdentity;
claimsIdentity.AddClaim(new Claim("id_token",
context.Request.Headers["Authorization"][0].Substring(context.AuthenticationTicket.AuthenticationScheme.Length + 1)));
// OPTIONAL: you can read/modify the claims that are populated based on the JWT
// claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, claimsIdentity.FindFirst("name").Value));
return Task.FromResult(0);
}
};
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" });
});
}