public JwtBearerTokenAuthenticationOptions(JwtOptions jwtOptions) { if (jwtOptions == null) { throw new ArgumentNullException("jwtOptions"); } byte[] symmetricKeyBytes = Encoding.UTF8.GetBytes(jwtOptions.JwtSigningKeyAsUtf8); string symmetricKeyAsBase64 = Convert.ToBase64String(symmetricKeyBytes); var symmetricKeyIssuerSecurityTokenProvider = new SymmetricKeyIssuerSecurityTokenProvider( jwtOptions.Issuer, symmetricKeyAsBase64); var providers = new IIssuerSecurityTokenProvider[] { symmetricKeyIssuerSecurityTokenProvider }; _jwtBearerOptions = new JwtBearerAuthenticationOptions { AllowedAudiences = new List<string> { jwtOptions.Audience }, IssuerSecurityTokenProviders = providers }; _jwtOptions = jwtOptions; }
public static IAppBuilder UseJsonWebToken(this IAppBuilder app, string issuer, string audience, X509Certificate2 signingKey, OAuthBearerAuthenticationProvider location = null) { if (app == null) { throw new ArgumentNullException("app"); } var options = new JwtBearerAuthenticationOptions { AllowedAudiences = new[] { audience }, IssuerSecurityTokenProviders = new[] { new X509CertificateSecurityTokenProvider( issuer, signingKey) } }; if (location != null) { options.Provider = location; } app.UseJwtBearerAuthentication(options); return app; }
/// <summary> /// Adds JWT bearer token middleware to your web application pipeline. /// </summary> /// <param name="app">The IAppBuilder passed to your configuration method.</param> /// <param name="options">An options class that controls the middleware behavior.</param> /// <returns>The original app parameter.</returns> public static IAppBuilder UseJwtBearerAuthentication(this IAppBuilder app, JwtBearerAuthenticationOptions options) { if (app == null) { throw new ArgumentNullException("app"); } if (options == null) { throw new ArgumentNullException("options"); } var bearerOptions = new OAuthBearerAuthenticationOptions { Realm = options.Realm, Provider = options.Provider, AccessTokenFormat = new JwtFormat(options.AllowedAudiences, options.IssuerSecurityTokenProviders), AuthenticationMode = options.AuthenticationMode, AuthenticationType = options.AuthenticationType, Description = options.Description }; app.UseOAuthBearerAuthentication(bearerOptions); return app; }
public static IAppBuilder UseJsonWebToken(this IAppBuilder app, string issuer, string audience, string signingKey, string type = null, OAuthBearerAuthenticationProvider location = null) { if (app == null) { throw new ArgumentNullException("app"); } var options = new JwtBearerAuthenticationOptions { AllowedAudiences = new[] { audience }, IssuerSecurityTokenProviders = new[] { new SymmetricKeyIssuerSecurityTokenProvider( issuer, signingKey) } }; if (!string.IsNullOrEmpty(type)) { options.AuthenticationType = type; } if (location != null) { options.Provider = location; } app.UseJwtBearerAuthentication(options); return app; }
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 = "" //}); }
private static void SetUpMiddleware(IAppBuilder app) { var jwtOptions = new JwtBearerAuthenticationOptions { AllowedAudiences = new List<string> {IdentityConstants.AllowedAudienceCode }, IssuerSecurityTokenProviders = new[] {new SymmetricKeyIssuerSecurityTokenProvider (IdentityConstants.Issuer, IdentityConstants.TokenSigningKey) }, Provider = new BearerTokenQueryStringInterceptor() }; app.UseJwtBearerAuthentication(jwtOptions); }
public void SymmetricJwtTokenAuthenticationWithProviderConfiguration(IAppBuilder app) { string issuer = "http://katanatesting.com/"; var signingAlgorithm = new AesManaged(); var SymmetricJwtOptions = new JwtBearerAuthenticationOptions() { AllowedAudiences = new string[] { issuer }, IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[] { new SymmetricKeyIssuerSecurityTokenProvider(issuer, signingAlgorithm.Key) }, Provider = new OAuthBearerAuthenticationProvider() { OnRequestToken = context => { context.OwinContext.Set<bool>("OnRequestToken", true); return Task.FromResult(0); }, OnValidateIdentity = context => { context.OwinContext.Set<bool>("OnValidateIdentity", true); return Task.FromResult(0); } } }; //This test is to demonstrate the use of this extension method app.UseJwtBearerAuthentication(SymmetricJwtOptions); app.Map("/BearerAuthenticationToken", subApp => { subApp.Run(async context => { var identity = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, "test") }, SymmetricJwtOptions.AuthenticationType, ClaimTypes.Name, ClaimTypes.Role); identity.AddClaim(new Claim(identity.RoleClaimType, "Guest", ClaimValueTypes.String)); var ticket = bool.Parse(context.Request.Query["issueExpiredToken"]) ? new AuthenticationTicket(identity, new AuthenticationProperties() { ExpiresUtc = DateTime.UtcNow }) : new AuthenticationTicket(identity, new AuthenticationProperties() { ExpiresUtc = DateTime.UtcNow.AddYears(4) }); var signingCredentials = new SigningCredentials(new InMemorySymmetricSecurityKey(signingAlgorithm.Key), SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest); await context.Response.WriteAsync(SecurityUtils.CreateJwtToken(ticket, issuer, signingCredentials)); }); }); app.UseBearerApplication(); }
public static void Register(IAppBuilder app, IContainer container) { var oAuthAuthorizationServerOptions = new OAuthAuthorizationServerOptions { AllowInsecureHttp = true, AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), Provider = container.Resolve<IOAuthAuthorizationServerProvider>(), AccessTokenFormat = container.Resolve<ISecureDataFormat<AuthenticationTicket>>() }; app.UseOAuthAuthorizationServer(oAuthAuthorizationServerOptions); var jwtBearerAuthenticationOptions = new JwtBearerAuthenticationOptions { AllowedAudiences = new List<string> { "HaloOnlineUser" }, AuthenticationMode = AuthenticationMode.Active, AuthenticationType = "Bearer", TokenValidationParameters = container.Resolve<TokenValidationParameters>(), IssuerSecurityTokenProviders = new List<IIssuerSecurityTokenProvider> { container.Resolve<IIssuerSecurityTokenProvider>() }, TokenHandler = container.Resolve<JwtSecurityTokenHandler>(), Provider = new OAuthBearerAuthenticationProvider { OnApplyChallenge = context => Task.FromResult(0), OnRequestToken = context => { var userContext = context.Request.Headers["USER_CONTEXT"]; if (!string.IsNullOrWhiteSpace(userContext)) { context.Token = userContext; } return Task.FromResult(0); }, OnValidateIdentity = context => Task.FromResult(0) } }; app.UseJwtBearerAuthentication(jwtBearerAuthenticationOptions); }
private void ConfigureOAuthTokenConsumption(IAppBuilder app) { var issuer = "http://localhost:4700"; string audienceId = ConfigurationManager.AppSettings["as:AudienceId"]; byte[] audienceSecret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["as:AudienceSecret"]); JwtBearerAuthenticationOptions JWToptions = new JwtBearerAuthenticationOptions() { AuthenticationMode = AuthenticationMode.Active, AllowedAudiences = new[] { audienceId }, IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[] { new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecret) }, Provider = new QueryStringOAuthBearerProvider(OAuthQueryStringName) }; // Api controllers with an [Authorize] attribute will be validated with JWT app.UseJwtBearerAuthentication(JWToptions); app.Map("/signalr", map => { // Setup the CORS middleware to run before SignalR. // By default this will allow all origins. You can // configure the set of origins and/or http verbs by // providing a cors options with a different policy. map.UseCors(CorsOptions.AllowAll); map.UseJwtBearerAuthentication(JWToptions); var hubConfiguration = new HubConfiguration { Resolver = GlobalHost.DependencyResolver, // You can disable JSONP by commenting line below. // JSONP requests are insecure but some older browsers (and some // versions of IE) require JSONP to work cross domain EnableJSONP = true, EnableDetailedErrors = true }; map.RunSignalR(hubConfiguration); }); }
private static void ConfigureOAuthConsumption(IAppBuilder app, JwtBearerAuthenticationOptions jwtBearerAuthenticationOptions) { // Api controllers with an [Authorize] attribute will be validated with JWT app.UseJwtBearerAuthentication(jwtBearerAuthenticationOptions); }
//private void ConfigureWebApi(HttpConfiguration config) //{ // config.MapHttpAttributeRoutes(); // var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First(); // jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; // GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter); // config.Routes.MapHttpRoute( // name: "DefaultApi", // routeTemplate: "api/{controller}/{id}", // defaults: new { id = RouteParameter.Optional } // ); //} private void ConfigureOAuthTokenConsumption(IAppBuilder app) { //use a cookie to temporarily store information about a user logging in with a third party login provider app.UseExternalSignInCookie(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie); var issuer = "http://localhost:9594"; string audienceId = ConfigurationManager.AppSettings["as:AudienceId"]; byte[] audienceSecret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["as:AudienceSecret"]); // Api controllers with an [Authorize] attribute will be validated with JWT OAuthBearerOptions = new JwtBearerAuthenticationOptions { AuthenticationMode = AuthenticationMode.Active, AllowedAudiences = new[] { audienceId }, IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[] { new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecret) } }; app.UseJwtBearerAuthentication(OAuthBearerOptions); }