本文整理汇总了C#中IAppBuilder.UseJwtBearerAuthentication方法的典型用法代码示例。如果您正苦于以下问题:C# IAppBuilder.UseJwtBearerAuthentication方法的具体用法?C# IAppBuilder.UseJwtBearerAuthentication怎么用?C# IAppBuilder.UseJwtBearerAuthentication使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IAppBuilder
的用法示例。
在下文中一共展示了IAppBuilder.UseJwtBearerAuthentication方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Configuration
public void Configuration(IAppBuilder app)
{
StagedDbContext.Instance.InitializeDatabase();
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseSignalRNotificationMiddleware();
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Passive,
AllowedAudiences = new[] { IdentityProviders.StagedClient.Key },
IssuerSecurityTokenProviders = new[]
{
new SymmetricKeyIssuerSecurityTokenProvider(IdentityProviders.StagedTokenIssuer, Convert.FromBase64String(ConfigurationManager.AppSettings["signing_key"]))
}
});
app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromHours(8),
Provider = new StagedAuthorizationServerProvider(),
AccessTokenFormat = new JsonWebTokenFormat(new JwtSecurityTokenHandler(), IdentityProviders.StagedTokenIssuer, IdentityProviders.StagedClient.Key)
});
app.SetupWebApiServices();
app.CacheMetadata();
}
示例2: ConfigureOAuth
public void ConfigureOAuth(IAppBuilder app)
{
var issuer = "http://jwtauthzsrv.azurewebsites.net";
var audience = "099153c2625149bc8ecb3e85e03f0022";
var secret = TextEncodings.Base64Url.Decode("IxrAjDoa2FqElO7IhrSrUJELhUckePEPVpaePlS_Xaw");
// Api controllers with an [Authorize] attribute will be validated with JWT
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] { audience },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
},
Provider = new OAuthBearerAuthenticationProvider
{
OnValidateIdentity = context =>
{
context.Ticket.Identity.AddClaim(new System.Security.Claims.Claim("newCustomClaim", "newValue"));
return Task.FromResult<object>(null);
}
}
});
}
示例3: Configuration
public void Configuration(IAppBuilder app)
{
var issuer = WebConfigurationManager.AppSettings["Auth0Domain"];
var audience = WebConfigurationManager.AppSettings["Auth0ClientID"];
var secret = TextEncodings.Base64Url.Decode(
WebConfigurationManager.AppSettings["Auth0ClientSecret"]);
app.UseCors(CorsOptions.AllowAll);
// Api controllers with an [Authorize] attribute will be validated with JWT
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] { audience },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
},
});
HttpConfiguration configuration = new HttpConfiguration();
configuration.MapHttpAttributeRoutes();
configuration.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
app.UseWebApi(configuration);
}
示例4: Configuration
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Filters.Add(new HostAuthenticationFilter("Bearer"));
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
AllowedAudiences = new []
{
"http://resourceserver.example"
},
IssuerSecurityTokenProviders = new []
{
new SymmetricKeyIssuerSecurityTokenProvider("http://authzserver.example", "CDDK7wUSy1jKkw3ymWiPL/Ovgfgqid1QtBsFf47wCQE=")
},
Realm = "resourceserver.example",
AuthenticationMode = AuthenticationMode.Passive
});
app.UseWebApi(config);
Console.WriteLine("Configuration is done");
}
示例5: Register
public static void Register(IAppBuilder app)
{
var config = new HttpConfiguration();
app.UseCors(CorsOptions.AllowAll);
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
string issuer = TokenConfig.TokenIssuerName;
string audience = TokenConfig.TokenIssuerName;
var secret = Encoding.UTF8.GetBytes(TokenConfig.PrivateKey);
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] { audience },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
}
});
}
示例6: Configure
public static void Configure(IAppBuilder app)
{
var issuer = WebConfigurationManager.AppSettings["JwtIssuer"];
var audience = WebConfigurationManager.AppSettings["JwtAudience"];
var secret = TextEncodings.Base64Url.Decode(WebConfigurationManager.AppSettings["JwtSecret"]);
// Api controllers with an [Authorize] attribute will be validated with JWT
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] { audience },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
},
Provider = new OAuthBearerAuthenticationProvider
{
OnRequestToken = context =>
{
var token = context.Token;
return Task.FromResult<object>(null);
},
// Provides opportunity to add claims to context.Ticket.Identity
OnValidateIdentity = context => Task.FromResult<object>(null)
}
});
}
示例7: Configuration
public void Configuration(IAppBuilder app)
{
app.Use<LoggingMiddleware>();
// Commenting the next line will fix the issue.
app.UseJwtBearerAuthentication(CreateJwtBearerAuthOptions());
app.UseNancy();
}
示例8: Configuration
public virtual void Configuration(IAppBuilder app)
{
HttpConfiguration config = GlobalConfiguration.Configuration;
config.DependencyResolver = new UnityDependencyResolver(UnityConfig.GetContainer());
app.UseJwtBearerAuthentication(new JwtOptions());
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
var jSettings = new JsonSerializerSettings();
jSettings.Formatting = Formatting.Indented;
jSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.Remove(config.Formatters.XmlFormatter);
config.Formatters.JsonFormatter.SerializerSettings = jSettings;
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
app.UseWebApi(config);
}
示例9: Configuration
public void Configuration(IAppBuilder appBuilder)
{
appBuilder.Use(async (context, next) =>
{
IOwinRequest req = context.Request;
IOwinResponse res = context.Response;
if (req.Path.StartsWithSegments(new PathString("/Token")))
{
var origin = req.Headers.Get("Origin");
if (!string.IsNullOrEmpty(origin))
{
res.Headers.Set("Access-Control-Allow-Origin", origin);
}
if (req.Method == "OPTIONS")
{
res.StatusCode = 200;
res.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Methods", "GET", "POST", "PUT", "DELETE");
res.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Headers", "authorization", "content-type");
return;
}
}
await next();
});
appBuilder.UseOAuthAuthorizationServer(new OAuthConfig());
appBuilder.UseJwtBearerAuthentication(new JwtOptions());
}
示例10: Configuration
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute("Api", "{Controller}");
config.EnableCors();
var issuer = ConfigurationManager.AppSettings["Issuer"];
var audience = ConfigurationManager.AppSettings["Audience"];
var signingCertificateSubjectDistinguishedName = ConfigurationManager.AppSettings["SigningCertificateSubjectDistinguishedName"];
var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
var certificate = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, signingCertificateSubjectDistinguishedName, true)[0];
// JSON should serialize to camelCase, not PascalCase (the default)
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
// Api controllers with an [Authorize] attribute will be validated with JWT
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] {audience},
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new X509CertificateSecurityTokenProvider(issuer, certificate),
//new X509CertificateSecurityTokenProvider(issuer, new X509Certificate2("PATH_TO_YOUR_PUBLIC_CERTIFICATE.cer")),
},
});
app.UseWebApi(config);
}
示例11: Install
public static new void Install(HttpConfiguration config, IAppBuilder app)
{
config.SuppressHostPrincipal();
SecurityApi.Services.Contracts.IIdentityService identityService = UnityConfiguration.GetContainer().Resolve<SecurityApi.Services.Contracts.IIdentityService>();
app.UseOAuthAuthorizationServer(new OAuthOptions(identityService));
app.UseJwtBearerAuthentication(new SecurityApi.Auth.JwtOptions());
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
var jSettings = new JsonSerializerSettings();
jSettings.Formatting = Formatting.Indented;
jSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.Remove(config.Formatters.XmlFormatter);
config.Formatters.JsonFormatter.SerializerSettings = jSettings;
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
示例12: ConfigureAuthZero
private void ConfigureAuthZero(IAppBuilder app)
{
// The keys and values are taken directly from Web.config.
var issuer = "https://" + ConfigurationManager.AppSettings["auth0:Domain"] + "/";
var audience = ConfigurationManager.AppSettings["auth0:ClientId"];
var secret =
TextEncodings.Base64.Encode(
TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["auth0:ClientSecret"]));
// We have to configure the web token barrier middleware to our Owin server.
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions()
{
// This configures the middleware to check every incoming request and attempt to authenticate
// the call and if it's successful, create a principal that represent a current user and assign
// that principal to the hosting environment.
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] { audience },
IssuerSecurityTokenProviders = new[]
{
// This will be used to sign the generated json web token.
new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
}
});
}
示例13: ConfigureAuth
public void ConfigureAuth(IAppBuilder app)
{
app.CreatePerOwinContext(DatabaseContext.Create);
app.CreatePerOwinContext<UserManager>(UserManager.Create);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
PublicClientId = "853749170e06bcda85f709b4a5a45c71"; //Also serves as key
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/api/1/login"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TokenTimeSpan,
//AllowInsecureHttp = !HttpsEnabled,
AllowInsecureHttp = true,
AccessTokenFormat = new JwtFormatProvider(TokenTimeSpan)
};
var issuer = "FireBreathingRubberDuckies";
var audience = "all";
var key = Convert.FromBase64String("4a3940a482cbe843ce0b6fefb938bf62");
JwtOptions = new JwtBearerAuthenticationOptions()
{
AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
AllowedAudiences = new[] { audience },
IssuerSecurityTokenProviders = new[]
{
new SymmetricKeyIssuerSecurityTokenProvider(issuer, key)
}
};
app.UseOAuthAuthorizationServer(OAuthOptions);
app.UseJwtBearerAuthentication(JwtOptions);
//app.UseMicrosoftAccountAuthentication(
// clientId: "",
// clientSecret: "");
//app.UseTwitterAuthentication(
// consumerKey: "",
// consumerSecret: "");
//app.UseFacebookAuthentication(
// appId: "",
// appSecret: "");
//app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
//{
// ClientId = "",
// ClientSecret = ""
//});
}
示例14: Configuration
// This method is required by Katana:
public void Configuration(IAppBuilder app)
{
app.CreatePerOwinContext<ISecurityProcessor>(() => new SecurityProcessor());
var webApiConfiguration = ConfigureWebApi();
app.UseOAuthAuthorizationServer(AuthorizationServerConfigurator.GetAuthorizationServerOptions());
app.UseJwtBearerAuthentication(AuthorizationServerConfigurator.JwtBearerAuthenticationOptions("Omnicell",
ConfigurationManager.AppSettings["AudienceId"],
ConfigurationManager.AppSettings["AudienceSecret"]));
app.UseWebApi(webApiConfiguration);
}
示例15: ConfigureOAuthTokenConsumption
/// <summary>
/// Configures how the web api should handle authorization.
/// The Api will now only trust issues by our Authorization Server and if Authorization Server = Resource Server
/// </summary>
/// <param name="app"></param>
private void ConfigureOAuthTokenConsumption(IAppBuilder app)
{
var issuer = ConfigurationManager.AppSettings["as:Issuer"];
// Api controllers with an [Authorize] attribute will be validated with JWT
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = Const.Audiences.Keys.ToArray(),
IssuerSecurityTokenProviders = Const.Audiences.Values.Select(x => new SymmetricKeyIssuerSecurityTokenProvider(issuer, TextEncodings.Base64Url.Decode(x))).ToArray()
});
}