Example #1
0
        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);
        }
Example #2
0
        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)
                    }
                });
        }
        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);
        }
Example #4
0
        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();
        }
Example #5
0
        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");
        }
Example #6
0
        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);
        }
        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)
                }

            });
        }
Example #8
0
        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)
                    }
                });
        }
        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());
        }
        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 }
                );
        }
 public void Configuration(IAppBuilder app)
 {
     app.Use<LoggingMiddleware>();
     // Commenting the next line will fix the issue.
     app.UseJwtBearerAuthentication(CreateJwtBearerAuthOptions());
     app.UseNancy();
 }
Example #12
0
        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);
                        }
                    }
                });
        }
        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 = ""
            //});
        }
        // 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);
        }
Example #15
0
    /// <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()
          });
    }
        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);
        }
        private void ConfigureAuthZero(IAppBuilder app)
        {
            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"]));

            app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Active,
                AllowedAudiences = new[] { audience },
                IssuerSecurityTokenProviders = new[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                }
            });
        }
Example #18
0
        private void ConfigureOAuthTokenConsumption(IAppBuilder app)
        {
            var issuer = "http://localhost:26573/";
            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
            app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Active,
                AllowedAudiences = new[] { audienceId },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                    {
                        new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecret)
                    }
            });
        }
Example #19
0
        public void ConfigureOAuth(IAppBuilder app)
        {
            const string issuer = "http://localhost:2194";
            const string audience = "d3c2e8f35db549df8b6507f7e025301d";
            var secret = TextEncodings.Base64Url.Decode("77WQguvGb_VS60ugvxT78i3ugL34ZgBLYygxtBMpsC0");

            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
                {
                    AuthenticationMode = AuthenticationMode.Active,
                    AllowedAudiences = new[] { audience },
                    IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                    {
                        new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                    }
                });
        }
        public void ConfigureApiAuth(IAppBuilder app)
        {
            var issuer = WebConfigurationManager.AppSettings["auth0:Domain"];
            var audience = WebConfigurationManager.AppSettings["auth0:ClientId"];
            var secret = TextEncodings.Base64Url.Decode(WebConfigurationManager.AppSettings["auth0:ClientSecret"]);

            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
                {
                    AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
                    AllowedAudiences = new[] { audience },
                    IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                    {
                        new SymmetricKeyIssuerSecurityTokenProvider(string.Format("https://{0}/", issuer), secret)
                    }
                });
        }
Example #21
0
        /// <summary>
        /// Permite configurar el proceso de validacion para todos los controladores de tipo API que esten marcados con [Authorize].
        /// </summary>
        /// <param name="app">Aplicacion</param>
        private void ConfigureOAuthTokenConsumption(IAppBuilder app)
        {
            string issueServer = ConfigurationManager.AppSettings["as:IssueServer"];
            string audienceId = ConfigurationManager.AppSettings["as:AudienceId"];
            byte[] audienceSecret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["as:AudienceSecret"]);

            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
                {
                    AuthenticationMode = AuthenticationMode.Active,
                    AllowedAudiences = new[] { audienceId },
                    IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                    {
                        new SymmetricKeyIssuerSecurityTokenProvider(issueServer, audienceSecret)
                    }
                });
        }
        public override void Configure(IAppBuilder app)
        {
            var jwtParams = new System.IdentityModel.Tokens.TokenValidationParameters
            {
                NameClaimType = NameClaimType,
                RoleClaimType = RoleClaimType,
                ValidAudience = Audience,
                ValidIssuer = Issuer,
            };
            if (SigningCert != null)
            {
                jwtParams.IssuerSigningToken = new X509SecurityToken(SigningCert);
            }
            else
            {
                var bytes = Convert.FromBase64String(SigningKey);
                jwtParams.IssuerSigningToken = new BinarySecretSecurityToken(bytes);
            }

            app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
            {
                TokenValidationParameters = jwtParams
            });
            app.RequireScopes(new ScopeValidationOptions
            {
                AllowAnonymousAccess = true,
                Scopes = new string[] {
                        Scope
                }
            });
            if (ClaimsTransformation != null)
            {
                app.Use(async (ctx, next) =>
                {
                    var user = ctx.Authentication.User;
                    if (user != null)
                    {
                        user = ClaimsTransformation(user);
                        ctx.Authentication.User = user;
                    }

                    await next();
                });
            }
        }
Example #23
0
        private void ConfigureAuthZero(IAppBuilder app)
        {
            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"]));

            // Api controllers with an [Authorize] attribute will be validated with JWT
            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
                {
                    AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
                    AllowedAudiences = new[] { audience },
                    IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                    {
                        new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                    }
                });
        }
Example #24
0
        // This should be on Resource Server , where AudienceId is to validate the resource Server through Authorization Server
        private void ConfigureOAuthTokenConsumption(IAppBuilder app)
        {
            var issuer = "http://localhost:53910"; // AUTHORIZATION SERVER
            var audience = "099153c2625149bc8ecb3e85e03f0022"; // AUDIENCE ID
            var secret = TextEncodings.Base64Url.Decode("IxrAjDoa2FqElO7IhrSrUJELhUckePEPVpaePlS_Xaw"); // AUDIENCE SECRET

            // 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)
                    }
                });
        }
Example #25
0
        private void ConfigureOAuthTokenConsumption(IAppBuilder app)
        {
            var issuer = Properties.ProjectUrl;
            string audienceId = Properties.AudienceId;
            byte[] audienceSecret = TextEncodings.Base64Url.Decode(Properties.AudienceSecret);

            // Api controllers with an [Authorize] attribute will be validated with JWT
            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
                {
                    AuthenticationMode = AuthenticationMode.Active,
                    AllowedAudiences = new[] { audienceId },
                    IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                    {
                        new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecret)
                    }
                });
        }
        public static void ConfigureOAuthTokenConsumption(IAppBuilder app)
        {
            var issuer = "ngKBaseAngular";
            string audienceId = ConfigurationManager.AppSettings["as:AudienceId"];
            byte[] audienceSecret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["as:AudienceSecret"]);

            // Ensures API [Authorize] attribute will be validated via JWT
            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
                {
                    AuthenticationMode = AuthenticationMode.Active,
                    AllowedAudiences = new[] { audienceId },
                    IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                    {
                        new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecret)
                    }
                });
        }
Example #27
0
        private static void _ConfigureJwtTokenConsumption(IAppBuilder app)
        {
            //JWT token consumption
            var issuer = ConfigurationManager.AppSettings["appRootUrl"];
            var audienceId = ConfigurationManager.AppSettings["as:AudienceId"];
            byte[] audienceSecret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["as:AudienceSecret"]);

            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
                {
                    AuthenticationMode = AuthenticationMode.Active,
                    AllowedAudiences = new[] { audienceId },
                    IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                    {
                        new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecret)
                    }
                });
        }
Example #28
0
        public void Configuration(IAppBuilder app)
        {
            //Set Up CORS
            var appSettings = WebConfigurationManager.AppSettings;
            var policy = new CorsPolicy
            {
                AllowAnyHeader = true,
                AllowAnyMethod = true,
                AllowAnyOrigin = true, // False by default, just left it here.
                SupportsCredentials = true
            };

            app.UseCors(new CorsOptions
            {
                PolicyProvider = new CorsPolicyProvider
                {
                    PolicyResolver = context => Task.FromResult(policy)
                }
            });

            MyHttpConfiguration config = new MyHttpConfiguration();

            try
            {
                app.UseOAuthAuthorizationServer(new SecOAuthOptions());
                app.UseJwtBearerAuthentication(new SecJwtOptions());

            }
            catch (Exception e)
            {
                throw e;
            }

            AreaRegistration.RegisterAllAreas();

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
              //  BundleConfig.RegisterBundles(BundleTable.Bundles);

            UnityConfig.RegisterComponents(config);

            app.UseWebApi(config);
        }
Example #29
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context and user manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

            app.UseCors(CorsOptions.AllowAll);

            PublicClientId = "self";

            OAuthBearerOptions = new SatellizerJwtBearerOptions("localhost", PublicClientId,
                "+UX5jSMcWqjNVJED2t4JLjtwCkcqxA7al3M5APPLtNK=", TimeSpan.FromHours(1));

            app.UseJwtBearerAuthentication(OAuthBearerOptions);

            GoogleOAuth2Handler.ClientId = "631036554609-v5hm2amv4pvico3asfi97f54sc51ji4o.apps.googleusercontent.com";
            GoogleOAuth2Handler.ClientSecret = "Google Client Secret";

        }
 private void ConfigureOAuthTokenConsumption(IAppBuilder app)
 {
     var issuer = "http://localhost:59822";
     string audienceId = "414e1927a3884f68abc79f7283837fd1";
     byte[] audienceSecret = TextEncodings.Base64Url.Decode("qMCdFDQuF23RV1Y-1Gq9L3cF3VmuFwVbam4fMTdAfpo");
     //var issuer = ConfigurationManager.AppSettings["as:TokenIssuer"];
     //string audienceId = ConfigurationManager.AppSettings["as:AudienceId"];
     //byte[] audienceSecret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["as:AudienceSecret"]);
     app.UseJwtBearerAuthentication(
         new JwtBearerAuthenticationOptions
         {
             AuthenticationMode = AuthenticationMode.Active,
             AllowedAudiences = new[] { audienceId },
             IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
             {
                 new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecret)
             }
         });
 }
Example #31
0
        private void ConfigureOAuthTokenConsumption(IAppBuilder app)
        {
            var    issuer     = "http://localhost/LinkManager";
            string audienceId = ConfigurationManager.AppSettings["as:AudienceId"];

            byte[] audienceSecret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["as:AudienceSecret"]);
            //var audienceSecret = new byte[64];

            // Api controllers with an [Authorize] attribute will be validated with JWT
            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
            {
                AuthenticationMode           = AuthenticationMode.Active,
                AllowedAudiences             = new[] { audienceId },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecret)
                }
            });
        }
Example #32
0
        public void ConfigureAuthApp(IAppBuilder appBuilder)
        {
            string UrlAddress = ConfigurationManager.AppSettings["BaseUri"].ToString();
            JwtBearerAuthenticationOptions jwtBearerAuthenticationOptions = new JwtBearerAuthenticationOptions();

            jwtBearerAuthenticationOptions.TokenValidationParameters =
                new TokenValidationParameters
            {
                ValidateIssuer           = true,
                ValidateAudience         = true,
                ValidateLifetime         = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer      = UrlAddress,
                ValidAudience    = UrlAddress,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("PlatformSecretKey"))
            };


            appBuilder.UseJwtBearerAuthentication(jwtBearerAuthenticationOptions);
        }
Example #33
0
        private void ConfigureAuthZero(IAppBuilder app)
        {
            var domain        = "https://" + ConfigurationManager.AppSettings["auth0:Domain"] + "/";
            var apiIdentifier = ConfigurationManager.AppSettings["auth0:ClientId"];

            // Api controllers with an [Authorize] attribute will be validated with JWT
            var keyResolver = new OpenIdConnectSigningKeyResolver(domain);

            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
            {
                AuthenticationMode        = AuthenticationMode.Active,
                TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidAudience            = apiIdentifier,
                    ValidIssuer              = domain,
                    IssuerSigningKeyResolver = (token, securityToken, identifier, parameters) => keyResolver.GetSigningKey(identifier)
                }
            });
        }
Example #34
0
        private void ConfigureAuth(IAppBuilder app)
        {
            // This should all really be loaded from a configuration file
            issuer   = "https://nf-eesquibel.mshome.net/Example/";                                                         // arbitrary URI
            audience = "https://nf-eesquibel.mshome.net/Example/";                                                         // arbitrary string or Uri that identifies this specific resource
            secret   = TextEncodings.Base64Url.Decode("p/MLeU433JN5pOYcqaRleFRK2OX6nSMnXMUsEDlkle35lUrEqAuF4iFp8EWfCZ1R"); // 48 random bytes

            app.UseJwtBearerAuthentication
            (
                new JwtBearerAuthenticationOptions
            {
                AuthenticationMode         = AuthenticationMode.Active,
                AllowedAudiences           = new[] { audience },
                IssuerSecurityKeyProviders = new IIssuerSecurityKeyProvider[]
                {
                    new SymmetricKeyIssuerSecurityKeyProvider(issuer, secret)
                }
            }
            );
        }
Example #35
0
        private static void ConfigureOAuthTokenConsumption(IAppBuilder app)
        {
            var    issuer     = System.Web.HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
            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
            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
            {
                AuthenticationMode           = AuthenticationMode.Active,
                AllowedAudiences             = new[] { audienceId },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecret)
                }
            });
        }
Example #36
0
        //private void ConfigureOAuthTokenGeneration(IAppBuilder app)
        //{
        //    // Configure the db context and user manager to use a single instance per request
        //    app.CreatePerOwinContext(ApplicationDbContext.Create);
        //    app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

        //    OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
        //    {
        //        //For Dev enviroment only (on production should be AllowInsecureHttp = false)
        //        AllowInsecureHttp = true,
        //        TokenEndpointPath = new PathString("/oauth/token"),
        //        AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
        //        Provider = new CustomOAuthProvider(),
        //        AccessTokenFormat = new CustomJwtFormat("http://localhost:59822")
        //    };

        //    // OAuth 2.0 Bearer Access Token Generation
        //    app.UseOAuthAuthorizationServer(OAuthServerOptions);
        //}
        private void ConfigureOAuthTokenConsumption(IAppBuilder app)
        {
            var issuer = "http://localhost:59822";//generate audienceid and secret from
            //https://github.com/tjoudeh/JWTAspNetWebApi/blob/master/AuthorizationServer.Api/AudiencesStore.cs#l24-34
            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
            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
            {
                AuthenticationMode           = AuthenticationMode.Active,
                AllowedAudiences             = new[] { audienceId },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecret)
                }
            });
        }
Example #37
0
        private void ConfigureOAuthTokenConsumption(IAppBuilder app)
        {
            string issuer     = ConfigurationManager.AppSettings["as:Issuer"];
            string audienceId = ConfigurationManager.AppSettings["as:AudienceId"];

            byte[] audienceSecret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["as:AudienceSecret"]);

            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
            {
                AuthenticationMode           = AuthenticationMode.Active,
                AllowedAudiences             = new[] { audienceId },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecret),
                    new CustomIssuerSecurityTokenProvider(issuer)
                },
                Provider = new CustomOAuthBearerProvider()
            });
        }
Example #38
0
        public void ConfigureAuth(IAppBuilder app)
        {
            var issuerV1 = ConfigurationManager.AppSettings["TokenIssuerV1"];
            var issuerV2 = ConfigurationManager.AppSettings["TokenIssuerV2"];

            var audience_clientdId = "iJbqXTj9oETMZZWW7q6cRCygNQ4VC0oU";
            var key_clientdSecret  = Convert.FromBase64String("Fw5E0kHY6O2XpQD4dkbXRuWctHNYYTkmwUdIDxSI9soD4X9yZOzm6Hgt8iXCRrEp");
            var x = new JwtBearerAuthenticationOptions
            {
                AuthenticationMode           = AuthenticationMode.Active,
                AllowedAudiences             = new[] { audience_clientdId },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuerV1, key_clientdSecret),   // V1 token for backward compatibility
                    new SymmetricKeyIssuerSecurityTokenProvider(issuerV2, key_clientdSecret)    // V2 token
                }
            };

            app.UseJwtBearerAuthentication(x);
        }
Example #39
0
        private void ConfigureOAuthTokenConsumption(IAppBuilder app)
        {
            var    issuer     = $"http://{System.Web.HttpContext.Current.Request.Url.Host}:{System.Web.HttpContext.Current.Request.Url.Port}"; //"http://localhost:53662";
            string audienceId = ConfigurationManager.AppSettings["AudienceId"];

            byte[] audienceSecret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["AudienceSecret"]);

            // Api controllers with an [Authorize] attribute will be validated with JWT
            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
            {
                AuthenticationMode           = AuthenticationMode.Active,
                AllowedAudiences             = new[] { audienceId },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecret)
                },
                TokenHandler = new CustomJwtTokenHandler()
            });
        }
Example #40
0
        public void Configuration(IAppBuilder app)
        {
            var domain        = $"https://{ConfigurationManager.AppSettings["Auth0Domain"]}/";
            var apiIdentifier = ConfigurationManager.AppSettings["Auth0ApiIdentifier"];

            string certificatePath = HostingEnvironment.MapPath("~/shariahstandards.cer");
            var    certificate     = new X509Certificate2(certificatePath);

            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
            {
                AuthenticationMode        = AuthenticationMode.Active,
                TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidAudience            = apiIdentifier,
                    ValidIssuer              = domain,
                    IssuerSigningKeyResolver = (a, b, c, d) => { return(new[] { (Microsoft.IdentityModel.Tokens.SecurityKey)(new X509SecurityKey(certificate)) }); },
                }
            });

            // Configure Web API
            WebApiConfig.Configure(app);
            //var issuer = $"https://{ConfigurationManager.AppSettings["Auth0Domain"]}/";
            //var audience = ConfigurationManager.AppSettings["Auth0ClientID"];

            // Api controllers with an [Authorize] attribute will be validated with JWT
            //app.UseActiveDirectoryFederationServicesBearerAuthentication(
            //    new ActiveDirectoryFederationServicesBearerAuthenticationOptions
            //    {
            //        TokenValidationParameters = new TokenValidationParameters
            //        {
            //            ValidAudience = audience,
            //            ValidIssuer = issuer,
            //            IssuerSigningKeyResolver = (token, securityToken, identifier, parameters) => parameters.IssuerSigningTokens.FirstOrDefault()?.SecurityKeys?.FirstOrDefault()
            //        },
            // Setting the MetadataEndpoint so the middleware can download the RS256 certificate
            //MetadataEndpoint = $"{issuer.TrimEnd('/')}/wsfed/{audience}/FederationMetadata/2007-06/FederationMetadata.xml"
            //    });
            //// Configure Web API
            //WebApiConfig.Configure(app);
        }
Example #41
0
        public static void AttachAuthenticationModules(this IAppBuilder app)
        {
            var config = ConfigurationManager.GetSection("authenticationMiddleware") as AuthenticationModulesConfigurationSection;

            if (config != null)
            {
                Logger.Info("Loaded {0} authentication modules", config.Modules.Count);
                foreach (ProviderSettings moduleElement in config.Modules)
                {
                    if (moduleElement.Type != null)
                    {
                        JwtBearerAuthenticationOptions jwtBearerAuthenticationOptions = null;

                        try
                        {
                            jwtBearerAuthenticationOptions =
                                Activator.CreateInstance(Type.GetType(moduleElement.Type)) as JwtBearerAuthenticationOptions;
                        }
                        catch (Exception exception)
                        {
                        }

                        if (jwtBearerAuthenticationOptions != null)
                        {
                            app.UseJwtBearerAuthentication(jwtBearerAuthenticationOptions);
                        }
                        else
                        {
                            app.Use(Type.GetType(moduleElement.Type));
                        }


                        Logger.Debug("added {0}", moduleElement.Name);
                    }
                }
            }
            else
            {
                throw new Exception("no authentication modules found");
            }
        }
Example #42
0
        public static void Install(HttpConfiguration config, IAppBuilder app)
        {
            WebApiUnityActionFilterProvider.RegisterFilterProviders(config);

            var container = UnityConfiguration.GetContainer();

            app.MapSignalR();

            config.Filters.Add(new HandleErrorAttribute(UnityConfiguration.GetContainer().Resolve <ILoggerFactory>()));

            app.UseCors(CorsOptions.AllowAll);

            config.SuppressHostPrincipal();

            var mediator = container.Resolve <IMediator>();
            Lazy <IAuthConfiguration> lazyAuthConfiguration = UnityConfiguration.GetContainer().Resolve <Lazy <IAuthConfiguration> >();

            config
            .EnableSwagger(c => c.SingleApiVersion("v1", "Backlog"))
            .EnableSwaggerUi();

            app.UseOAuthAuthorizationServer(new OAuthOptions(lazyAuthConfiguration, mediator));

            app.UseJwtBearerAuthentication(new JwtOptions(lazyAuthConfiguration));

            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            config.Filters.Add(new AuthorizeAttribute());


            var jSettings = new JsonSerializerSettings();

            jSettings.Formatting            = Formatting.Indented;
            jSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            jSettings.ContractResolver      = new SignalRContractResolver();
            config.Formatters.JsonFormatter.SerializerSettings = jSettings;

            config.Formatters.Remove(config.Formatters.XmlFormatter);

            config.MapHttpAttributeRoutes();
        }
Example #43
0
        public void Configuration(IAppBuilder app)
        {
            // Dependency injection settings
            var container = new UnityContainer();
            var config    = WebApiConfig.Register(container);

            app.Use <LoggingMiddleware>();
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
            //enable cors origin requestsit
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            /*var myProvider = new AuthorizationServerProvider();
             * OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
             * {
             *  AllowInsecureHttp = true,
             *  TokenEndpointPath = new PathString("/token"),
             *  AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),   // OAuth token valid 1 day
             *  Provider = myProvider,
             *  RefreshTokenProvider = new SimpleRefreshTokenProvider()
             * };
             * app.UseOAuthAuthorizationServer(options);
             * app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());*/
            app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
            {
                //AllowedAudiences = new[] { "KL²", "KL² Web Admin", "KL² Tablet" },
                TokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKey = JwtTokenProvider._jwtSecret.ToSymmetricSecurityKey(),
                    ValidIssuer      = JwtTokenProvider._appDomain,
                    ValidateAudience = false,
                    ValidateLifetime = true,
                    ClockSkew        = TimeSpan.FromMinutes(0)
                }
            });

            app.UseWebApi(config);
            app.MapSignalR(SignalRConfig.Register(container));

            // Setup Log4Net configuration (in App.config)
            log4net.Config.XmlConfigurator.Configure();
        }
        public void Configuration(IAppBuilder app)
        {
            var issuer   = $"https://{ConfigurationManager.AppSettings["Auth0Domain"]}/";
            var audience = ConfigurationManager.AppSettings["Auth0ClientID"];
            var secret   = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["Auth0ClientSecret"]);

            // 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)
                },
            });

            // Configure Web API
            WebApiConfig.Configure(app);
        }
Example #45
0
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888

            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions()
            {
                AuthenticationMode        = AuthenticationMode.Active,
                TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer       = VarsSubsFunc.mStrIssuerURL, // some string, normally web url,
                    ValidAudience     = VarsSubsFunc.mStrAudience,
                    IssuerSigningKey  = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(VarsSubsFunc.mStrSecretKey)),
                    ValidateLifetime  = true,
                    LifetimeValidator = LifetimeValidator
                }
            });
        }
        private void ConfigureOAuthTokenConsumption(IAppBuilder app)
        {
#if DEBUG
            var issuer = "http://localhost/NetDiet/Therapist";
#else
            var issuer = "http://mintest.dk/";
#endif
            string audienceId     = ConfigurationManager.AppSettings["as:AudienceId"];
            byte[] audienceSecret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["as:AudienceSecret"]);

            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
            {
                AuthenticationMode           = AuthenticationMode.Active,
                AllowedAudiences             = new[] { audienceId },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecret)
                }
            });
        }
Example #47
0
        public void ConfigureOAuth(IAppBuilder app)
        {
            var issuer   = ConfigurationManager.AppSettings[ConfigurationManager.AppSettings["currentApiSecurity"]];
            var AppUser  = TextEncodings.Base64Url.Decode("4e686af7bdcc5ae005a247624fd8c7283257c2514f6b3ad2ff5d4cb6d95196e6");
            var AppAdmin = TextEncodings.Base64Url.Decode("d4f0bc5a29de06b510f9aa428f1eedba926012b591fef7a518e776a7c9bd1824");
            var AdminWeb = TextEncodings.Base64Url.Decode("d4f0bc5a29de06b512389nsvdisvyr89qriojfsdiow32r98q4e776a7c9bd1824");

            // Api controllers with an [Authorize] attribute will be validated with JWT
            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
            {
                AuthenticationMode           = AuthenticationMode.Active,
                AllowedAudiences             = new[] { "099153c2625149bc8ecb3e85e03f0022", "cdb59355f3ba293977fc0945fb85f118", "cdb59355f3ba293977fc0945fb85aiop" },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, AppUser),
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, AppAdmin),
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, AdminWeb)
                }
            });
        }
Example #48
0
        public void ConfigureOauth(IAppBuilder app)
        {
            var issuer = ConfigurationManager.AppSettings["issuer"];
            var secret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["secret"]);

            AuthServerOptions.OabOpts = new OAuthBearerAuthenticationOptions();
            var serverOpts = new AuthServerOptions(issuer);


            app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
            {
                AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
                AllowedAudiences   = new[] { "Any" },

                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[] {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                }
            });

            app.UseOAuthAuthorizationServer(serverOpts.OauthOpts);
        }
Example #49
0
        public void Configuration(IAppBuilder app)
        {
            var issuer   = WebConfigurationManager.AppSettings["Auth0Domain"];
            var audience = WebConfigurationManager.AppSettings["Auth0ClientID"];
            var secret   = TextEncodings.Base64Url.Decode(WebConfigurationManager.AppSettings["Auth0ClientSecret"]);

            app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
            {
                AuthenticationMode           = AuthenticationMode.Active,
                AllowedAudiences             = new[] { audience },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[] {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                }
            });

            HttpConfiguration configuration = new HttpConfiguration();

            configuration.MapHttpAttributeRoutes();

            WebApiConfig.Register(configuration);
        }
Example #50
0
        public void Configuration(IAppBuilder app)
        {
            EnsureAuthIndexes.Exist();
            HttpConfiguration config = new HttpConfiguration();

            DataProtectionProvider = app.GetDataProtectionProvider();
            var container = SimpleInjectorInitializer.Initialize(config);

            IClientService clientService;

            using (container.BeginExecutionContextScope())
            {
                clientService = container.GetInstance <IClientService>();
            }

            WebApiConfig.Register(config);
            app.UseOAuthAuthorizationServer(OAuthTokenOptions(clientService));
            app.UseJwtBearerAuthentication(OAuthTokenConsumption());
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.UseWebApi(config);
        }
Example #51
0
 public void Configuration(IAppBuilder app)
 {
     // JWT Bearer
     if (ConfigurationManager.ConnectionStrings["JWTKey"] != null)
     {
         string key_s = ConfigurationManager.ConnectionStrings["JWTKey"].ConnectionString;
         byte[] key_b = System.Text.Encoding.UTF8.GetBytes(key_s);
         app.UseJwtBearerAuthentication(
             new Microsoft.Owin.Security.Jwt.JwtBearerAuthenticationOptions
         {
             TokenValidationParameters = new TokenValidationParameters
             {
                 IssuerSigningToken    = new BinarySecretSecurityToken(key_b),
                 RequireExpirationTime = true,
                 ValidateIssuer        = true,
                 ValidIssuer           = "http://testauth.plasne.com",
                 ValidateAudience      = false
             }
         });
     }
 }
Example #52
0
        internal static void ConfigureResourceServer(IAppBuilder app)
        {
            var issuer   = ConfigurationManager.AppSettings[Constants.AppSettings.AUTH_SERVER_TOKEN_ISSUER];
            var audience = "683DD6FEC91749DAA00B103BA026215C";

            var secret = Microsoft.Owin.Security.DataHandler.Encoder.TextEncodings.Base64Url.Decode("PKJHc8JIsdDICF+kzdfTui3BYaHyiFY10oxH1JVEsDQ=");

            var options = new JwtBearerAuthenticationOptions
            {
                AuthenticationMode           = AuthenticationMode.Active,
                AllowedAudiences             = new[] { audience },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                },
                Provider = new OAuthBearerAuthenticationProvider()
            };

            app.UseJwtBearerAuthentication(options);
            app.UseResourceAuthorization(new Gestion.Security.Authorization.GestionResourceAuthorizationManager());
        }
        public static void Register(IAppBuilder app)
        {
            List <X509SecurityKey> issuerSigningKeys = GetIssuerSigningKeys();

            app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Active,
                AllowedAudiences   = new[] { FirebaseValidAudience },
                Provider           = new OAuthBearerAuthenticationProvider
                {
                    OnValidateIdentity = OnValidateIdentity
                },
                TokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKeys        = issuerSigningKeys,
                    ValidAudience            = FirebaseValidAudience,
                    ValidIssuer              = FirebaseValidIssuer,
                    IssuerSigningKeyResolver = (arbitrarily, declaring, these, parameters) => issuerSigningKeys
                }
            });
        }
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888

            var tokenFromConfig = ConfigurationManager.AppSettings["SecretTokenKey"];

            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
            {
                AuthenticationMode        = AuthenticationMode.Active,
                TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    ValidateIssuerSigningKey = true,

                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
                                                                .GetBytes(tokenFromConfig))
                }
            });
        }
Example #55
0
        /// <summary>
        /// Cionfigure protection for Resource server resources using JWT
        /// </summary>
        /// <param name="app"></param>
        private static void RegisterResourceServer(IAppBuilder app)
        {
            // Configure our API to trust tokens issued by our Authorization server only,
            // in our case the Authorization and Resource Server are the same server
            var    issuer     = ConfigurationManager.AppSettings["as:Issuer"].ToString();
            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
            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
            {
                AuthenticationMode           = AuthenticationMode.Active,
                AllowedAudiences             = new[] { audienceId },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecret)
                }
            });
        }
Example #56
0
        public void Configuration(IAppBuilder app)
        {
            var key      = ConfigurationManager.AppSettings["JwtSymmetricSecurityKey"];
            var issuer   = ConfigurationManager.AppSettings["JwtIssuer"];
            var audience = ConfigurationManager.AppSettings["JwtAudience"];

            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
            {
                AuthenticationMode        = Microsoft.Owin.Security.AuthenticationMode.Active,
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = issuer,
                    ValidAudience    = audience,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key))
                }
            });
        }
Example #57
0
        // PRIVATE
        // =============================================================================================
        private void ConfigureOAuth(IAppBuilder app)
        {
            var issuer = ConfigurationManager.AppSettings["issuer"];
            var secret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["secret"]);

            app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/oauth2/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider          = new CustomOAuthProvider(),
                AccessTokenFormat = new CustomJwtFormat(issuer)
            });

            app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions {
                AuthenticationMode           = AuthenticationMode.Active,
                AllowedAudiences             = new[] { "Any" },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[] {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                }
            });
        }
Example #58
0
        public void Configuration(IAppBuilder appBuilder)
        {
            HttpConfiguration config = new HttpConfiguration();

            WebApiConfig.Register(config);

            appBuilder.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
            {
                AuthenticationMode        = AuthenticationMode.Active,
                TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = "http://localhost",
                    ValidAudience    = "http://localhost",
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("jwt_signing_secret_key"))
                }
            });
            appBuilder.UseWebApi(config);
        }
Example #59
0
        //OUE_GRAD_PROJECT_KEY";

        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey));

            app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
            {
                AuthenticationMode        = AuthenticationMode.Active,
                TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateIssuerSigningKey = true,
                    //set up Validate Data
                    ValidIssuer      = "smesk.in", //some string, normally web url,
                    ValidAudience    = "readers",
                    IssuerSigningKey = key
                }
            });
        }
Example #60
0
        public void ConfigureOAuth(IAppBuilder app)
        {
            var config = AppConfiguration.Config;

            var issuer    = config.JwtIssuer;
            var audience  = config.JwtAudienceKey;
            var secretRaw = config.JwtSecretKey;
            var secret    = TextEncodings.Base64Url.Decode(secretRaw);

            // 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)
                }
            });
        }