Example #1
2
        public void ConfigureOAuth(IAppBuilder app)
        {
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
            OAuthBearerOptions = new OAuthBearerAuthenticationOptions();

            OAuthAuthorizationServerOptions oAuthServerOptions = new OAuthAuthorizationServerOptions() {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                Provider = new SimpleAuthorizationServerProvider(),
                RefreshTokenProvider = new SimpleRefreshTokenProvider()
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(oAuthServerOptions);
            app.UseOAuthBearerAuthentication(OAuthBearerOptions);

            //Configure Google External Login
            googleAuthOptions = new GoogleOAuth2AuthenticationOptions() {
                ClientId = "xxx",
                ClientSecret = "xxx",
                Provider = new GoogleAuthProvider()
            };
            app.UseGoogleAuthentication(googleAuthOptions);

            //Configure Facebook External Login
            facebookAuthOptions = new FacebookAuthenticationOptions() {
                AppId = "xxx",
                AppSecret = "xxx",
                Provider = new FacebookAuthProvider()
            };
            app.UseFacebookAuthentication(facebookAuthOptions);
        }
        private void ConfigureOAuth(IAppBuilder app)
        {
            app.UseExternalSignInCookie(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie);
            OAuthBearerOptions = new OAuthBearerAuthenticationOptions();

            OAuthAuthorizationServerOptions oAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new SimpleAuthorizationServerProvider(new AccountRepository())
            };

            GoogleAuthOptions = new GoogleOAuth2AuthenticationOptions()
            {
                ClientId = "592613624399-a3gr6vveaocnptgvv6738rmnk0pb5cev.apps.googleusercontent.com",
                ClientSecret = "FqNKKib_BP7dsNYBoJa8NwUC",
                Provider = new GoogleAuthProvider()
            };
            app.UseGoogleAuthentication(GoogleAuthOptions);

            FacebookAuthOptions = new FacebookAuthenticationOptions()
            {
                AppId = "806191272841558",
                AppSecret = "1a8241e9d46c4a5e393ae51f265a3489",
                Provider = new FacebookAuthProvider()
            };
            app.UseFacebookAuthentication(FacebookAuthOptions);

            // Token Generation
            app.UseOAuthAuthorizationServer(oAuthServerOptions);
            app.UseOAuthBearerAuthentication(OAuthBearerOptions);
        }
Example #3
1
        public void ConfigureOAuth(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);
              OAuthBearerOptions = new OAuthBearerAuthenticationOptions();

              OAuthAuthorizationServerOptions oAuthServerOptions = new OAuthAuthorizationServerOptions()
              {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
            Provider = new SimpleAuthorizationServerProvider(),
            RefreshTokenProvider = new SimpleRefreshTokenProvider()
              };

              // Token Generation
              app.UseOAuthAuthorizationServer(oAuthServerOptions);
              app.UseOAuthBearerAuthentication(OAuthBearerOptions);

              //Configure Facebook External Login
              //FacebookAuthOptions = new FacebookAuthenticationOptions()
              //{
              //  AppId = "841670309262660",
              //  AppSecret = "8b4eba3df30d4aa95427fa9c90372462",
              //  Provider = new FacebookAuthProvider(),
              //  Scope = { "user_about_me", "user_friends", "email", "read_friendlists", "publish_stream", "user_birthday", "user_location" }
              //};

              //app.UseFacebookAuthentication(FacebookAuthOptions);
        }
Example #4
0
        public void ConfigureOAuth(IAppBuilder app)
        {
            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {

                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                Provider = new SimpleAuthorizationServerProvider(),
                RefreshTokenProvider = new SimpleRefreshTokenProvider()
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            //Configure Google External Login
            googleAuthOptions = new GoogleOAuth2AuthenticationOptions()
            {
                ClientId = "90666907944-o02ijc0nes4e6u26b7jmk7b6sr8dclr9.apps.googleusercontent.com",
                ClientSecret = "VwuUWkX4wCTn2UssEX4vfCP6",
                Provider = new GoogleAuthProvider()
            };
            app.UseGoogleAuthentication(googleAuthOptions);

            //Configure Facebook External Login
            facebookAuthOptions = new FacebookAuthenticationOptions()
            {
                AppId = "146338829036652",
                AppSecret = "4c24328bfaa6d1801a98e72d91c3c600",
                Provider = new FacebookAuthProvider()
            };
            app.UseFacebookAuthentication(facebookAuthOptions);
        }
        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());
        }
Example #6
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 #7
0
        public static void Configuration(IAppBuilder app)
        {
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            var OAuthOptions = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/oauth/Token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromHours(8),
                Provider = new Providers.MyAuthorizationServerProvider(),
                // RefreshTokenProvider = new Providers.MyRefreshTokenProvider(DateTime.UtcNow.AddHours(8))
            };
            app.UseOAuthAuthorizationServer(OAuthOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            // Configure Web API for self-host.
            HttpConfiguration config = new HttpConfiguration();

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

            // Web API routes
            config.MapHttpAttributeRoutes();

            // We don't need this crap anymore!
            //config.Routes.MapHttpRoute(
            //    name: "DefaultApi",
            //    routeTemplate: "api/{controller}/{id}",
            //    defaults: new { id = RouteParameter.Optional }
            //);

            app.UseWebApi(config);
        }
        private void ConfigureOAuth(IAppBuilder app) {
            var oAuthServerOptions = new OAuthAuthorizationServerOptions {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/api/account/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new AuthorizationServerProvider()
            };

            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
            app.UseOAuthAuthorizationServer(oAuthServerOptions);

            app.Use(async (context, next) =>
            {
                var request = context.Request;
                var response = context.Response;
                if (request.Path.StartsWithSegments(oAuthServerOptions.TokenEndpointPath)) {
                    var origin = request.Headers.Get("Origin");
                    if (!string.IsNullOrEmpty(origin)) {
                        response.Headers.Set("Access-Control-Allow-Origin", origin);
                    }
                    if (request.Method == "OPTIONS") {
                        response.StatusCode = 200;
                        response.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Methods", "GET", "POST");
                        response.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Headers", "authorization", "content-type");
                        return;
                    }
                }
                await next();
            });
        }
Example #9
0
        public void Configuration(IAppBuilder app)
        {
            SecurityConfig.Config();
            var oauthServerConfig = new Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = false,
                AccessTokenExpireTimeSpan = TimeSpan.FromHours(2),
                Provider = new AuthorizationServerProvider(),
                TokenEndpointPath = new PathString("/token")
            };
            app.UseOAuthAuthorizationServer(oauthServerConfig);

            var oauthConfig = new Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationOptions
            {
                AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active
                //AuthenticationType = "Bearer"
            };
            app.UseOAuthBearerAuthentication(oauthConfig);
            var config = new HttpConfiguration();
            WebApiConfig.Register(config);
            app.UseWebApi(config);
            GlobalHost.Configuration.ConnectionTimeout = TimeSpan.FromSeconds(1);
            GlobalHost.Configuration.LongPollDelay = TimeSpan.FromMilliseconds(5000);
            app.MapSignalR();
        }
Example #10
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.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            //app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Configure the application for OAuth based flow
            PublicClientId = "self";
            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                //Provider = new ApplicationOAuthProvider(PublicClientId),
                AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                AllowInsecureHttp = true
            };
            app.UseOAuthAuthorizationServer(OAuthOptions);

            // Enable the application to use bearer tokens to authenticate users
            //app.UseOAuthBearerTokens(OAuthOptions); ""
            //});
        }
        public void ConfigureOAuth(IAppBuilder app, HttpConfiguration config)
        {
            UserManagerFactory = () =>
            {
                try
                {
                    var userRepository = config.DependencyResolver.GetService(typeof(IUserRepository));
                    var userManager =
                        new ApplicationUserManager(userRepository as IUserRepository);
                    return userManager;
                }
                catch (Exception)
                {
                    return null;
                }
            };

            app.CreatePerOwinContext(UserManagerFactory);

            var oAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new SimpleAuthorizationProvider()
            };

            app.UseOAuthAuthorizationServer(oAuthServerOptions);

            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
Example #12
0
        // What is OAuth????
        //OAuth is an open standard for authorization. OAuth provides client applications
        //a 'secure delegated access' to server resources on behalf of a resource owner.
        //It specifies a process for resource owners to authorize third-party access to their
        //server resources without sharing their credentials.
        public void ConfigureOAuth(IAppBuilder app)
        {
            //Here we’ve created new instance from class “OAuthAuthorizationServerOptions”
            //and set its option as the below:

            //1.
            //The path for generating tokens will be as :”http://localhost:port/token”.
            //We’ll see how we will issue HTTP POST request to generate token in the next steps.

            //2.
            //We’ve specified the expiry for token to be 24 hours, so if the user tried
            //to use the same token for authentication after 24 hours from the issue time,
            //his request will be rejected and HTTP status code 401 is returned.

            //3.
            //We’ve specified the implementation on how to validate the credentials for
            //users asking for tokens in custom class named “SimpleAuthorizationServerProvider”.

            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                Provider = new SimpleAuthorizationServerProvider(),
                RefreshTokenProvider = new SimpleRefreshTokenProvider()
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
Example #13
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);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Configure the application for OAuth based flow
            PublicClientId = "self";
            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                Provider = new ApplicationOAuthProvider(PublicClientId),
                AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                // In production mode set AllowInsecureHttp = false
                AllowInsecureHttp = true
            };
            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthOptions);
            OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
            app.UseOAuthBearerAuthentication(OAuthBearerOptions);

            facebookAuthOptions = new FacebookAuthenticationOptions
            {
                AppId = "1543886725935090",
                AppSecret = "63ab7a49e991177caf72e3ec8f2247cc",
                Provider = new FacebookAuthProvider()
            };
            app.UseFacebookAuthentication(facebookAuthOptions);
        }
        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 }
                );
        }
Example #15
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            DataProtectionProvider = app.GetDataProtectionProvider();
            // Configure the db context and user manager to use a single instance per request
            //app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext(CreateKernel);
            app.UseNinjectMiddleware(CreateKernel);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Configure the application for OAuth based flow
            PublicClientId = "self";
            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                Provider = new ApplicationOAuthProvider(PublicClientId),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                AccessTokenFormat = new HunterJwtFormat("http://localhost:53147/"),
                // In production mode set AllowInsecureHttp = false
                AllowInsecureHttp = true
            };

            // Enable the application to use bearer tokens to authenticate users
            //app.UseOAuthBearerTokens(OAuthOptions);
            app.UseOAuthAuthorizationServer(OAuthOptions);
            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseLinkedInAuthentication(
            //    "<YOUR API KEY>",
            //    "<YOUR SECRET KEY>"
            //    );
        }
Example #16
0
        public void ConfigureOAuth(IAppBuilder app)
        {
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                Provider = new OAuthAuthorizationServerProvider
                {
                    OnValidateClientAuthentication = async c=>c.Validated(),
                    OnGrantResourceOwnerCredentials = async c =>
                    {
                        using (var repo = new AuthRepository())
                        {
                            var user = await repo.FindUser(c.UserName, c.Password);
                            if (user == null)
                            {
                                c.Rejected();
                                throw new ApiException("User not existed or wrong password.");
                            }
                        }
                        var identity = new ClaimsIdentity(c.Options.AuthenticationType);
                        identity.AddClaims(new[] {new Claim(ClaimTypes.Name, c.UserName), new Claim(ClaimTypes.Role, "user")});
                        if (string.Equals(c.UserName, AppConfig.Manager, StringComparison.InvariantCultureIgnoreCase))
                            identity.AddClaims(new[] {new Claim(ClaimTypes.Name, c.UserName), new Claim(ClaimTypes.Role, "manager")});
                        c.Validated(identity);
                    }
                },
            });
        }
Example #17
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {


            // app.CreatePerOwinContext<UserManager>(() => new UserManager(new UserStore()));
            // app.CreatePerOwinContext<Custom.Identity.RoleManager>(() => new Custom.Identity.RoleManager(new Custom.Identity.RoleStore()));
            //app.CreatePerOwinContext<SignInService>((options, context) => new SignInService(context.GetUserManager<UserManager>(), context.Authentication));

            app.UseExternalSignInCookie(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie);
            OAuthBearerOptions = new OAuthBearerAuthenticationOptions();


            var OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                Provider = new Api.Socioboard.App_Start.ApplicationOAuthServerProvider("self"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),

                // Only do this for demo!!
                AllowInsecureHttp = true
            };
            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthOptions);
            app.UseOAuthBearerAuthentication(OAuthBearerOptions);

        }
Example #18
0
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            // token consumption
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            var container = SimpleInjectorConfig.Register();
            var config = new HttpConfiguration
            {
                DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container)
            };
            WebApiConfig.Register(config);
            app.UseWebApi(config);

            Func<IUserService> userServiceFactory = () => container.GetInstance<IUserService>();
            app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
            {
                // for demo purposes
                AllowInsecureHttp = true,

                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromHours(8),

                Provider = new AuthorizationServerProvider(userServiceFactory)
            });
        }
        public static void ConfigureOAuthTokenGeneration(IAppBuilder app)
        {
            // configure database context and user manager to use a single instance per request
            app.CreatePerOwinContext(ngk.DataLayer.EFDbContext.AuthorizationContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

            app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

            var token = new CustomJwtFormat("ngKBaseAngular");

            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                // production should not allow insecure http
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(20),
                Provider = new Providers.CustomOAuthProvider(),
                RefreshTokenProvider = new Providers.RefreshTokenProvider(),
                AccessTokenFormat = token
            };

            // OAuth 2.0 Bearer Access Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
Example #20
0
        public void ConfigureOAuth(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Login"),
                Provider = new CookieAuthenticationProvider()
                {
                    OnApplyRedirect = ctx =>
                    {
                        if (!IsApiRequest(ctx.Request))
                        {
                            ctx.Response.Redirect(ctx.RedirectUri);
                        }
                    }
                }
            });

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            //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 OAuthBearerOptions = new OAuthBearerAuthenticationOptions();

            // Token Generation
            app.UseOAuthAuthorizationServer(NinjectResolver.CreateKernel.Value.Get<MyOAuthAuthorizationServerOptions>().GetOptions());
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions { Provider = new ApplicationOAuthBearerAuthenticationProvider()});
        }
Example #21
0
        public void ConfigureAuth(IAppBuilder app, HttpConfiguration config)
        {
            var userStore = config.DependencyResolver.GetService(typeof(IUserStore<ApplicationUser, Guid>)) as IUserStore<ApplicationUser, Guid>;
            var roleStore = config.DependencyResolver.GetService(typeof(IRoleStore<ApplicationRole, Guid>)) as IRoleStore<ApplicationRole, Guid>;

            UserManager = new UserManager<ApplicationUser, Guid>(userStore);
            RoleManager = new RoleManager<ApplicationRole, Guid>(roleStore);

            CompanyRepository = config.DependencyResolver.GetService(typeof(ICompanyRepository)) as ICompanyRepository;
            WidgetDefinitionRepository = config.DependencyResolver.GetService(typeof(IWidgetDefinitionRepository)) as IWidgetDefinitionRepository;

            var oAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/api/v1/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new SimpleAuthorizationServerProvider(UserManager)
            };

            // Adds OAuth server (token generation)
            app.UseOAuthAuthorizationServer(oAuthServerOptions);

            // Adds bearer token processing to pipeline (token consumption)
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            Seed();
        }
Example #22
0
        public void ConfigureAuth(IAppBuilder app)
        {
            var config = new HttpConfiguration();

            // TODO: figure out how to get client certificates
            // config.MessageHandlers.Add(new CertificateHandler());
            config.MessageHandlers.Add(new ValidateRequestHandler());

            OAuthBearerOptions = new OAuthAuthorizationServerOptions();
            app.UseOAuthAuthorizationServer(OAuthBearerOptions);

            OAuthBearerAuthenticationOptions = new OAuthBearerAuthenticationOptions();
            app.UseOAuthBearerAuthentication(OAuthBearerAuthenticationOptions);

            bool loadAssemblies = false;
            if (bool.TryParse(ConfigurationManager.AppSettings["LoadAssemblyForTest"], out loadAssemblies))
            {
                config.Services.Replace(typeof(IAssembliesResolver), new AssemblyResolver());
            }

            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter("Bearer"));

            app.UseWebApi(config);
        }
Example #23
0
        public void ConfigureOAuth(IAppBuilder app, IUserProvider userProvider)
        {
            var oAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/api/v1/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(7),
                Provider = new SimpleAuthorizationServerProvider(userProvider)
            };


            app.Use(async (context, next) =>
            {
                if (context.Request.QueryString.HasValue)
                {
                    if (string.IsNullOrWhiteSpace(context.Request.Headers.Get("Authorization")))
                    {
                        var queryString = HttpUtility.ParseQueryString(context.Request.QueryString.Value);
                        string token = queryString.Get("access_token");

                        if (!string.IsNullOrWhiteSpace(token))
                        {
                            context.Request.Headers.Add("Authorization", new[] { string.Format("Bearer {0}", token) });
                        }
                    }
                }

                await next.Invoke();
            });

            // Token Generation
            app.UseOAuthAuthorizationServer(oAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
Example #24
0
        public void ConfigureOAuth(IAppBuilder app)
        {
            app.UseExternalSignInCookie(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie);
            OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                Provider = new SimpleAuthorizationServerProvider(),
                RefreshTokenProvider = new SimpleRefreshTokenProvider()
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(OAuthBearerOptions);
            //Configure Google External Login
            googleAuthOptions = new GoogleOAuth2AuthenticationOptions()
            {
                ClientId = "936007638974-2ko9tqdmv3ifomlblhlrnninkdoe9bkt.apps.googleusercontent.com",
                ClientSecret = "4_GR4_4JPnglWQOnSnwOZzlV",
                Provider = new GoogleAuthProvider()
            };
            app.UseGoogleAuthentication(googleAuthOptions);
        }
Example #25
0
File: App.cs Project: MartinBG/Gva
        public static void ConfigureAuth(IAppBuilder app, IContainer container)
        {
            var sessionState = (SessionStateSection)WebConfigurationManager.GetSection("system.web/sessionState");

            app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/api/token"),
                Provider = container.Resolve<IOAuthAuthorizationServerProvider>(),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(sessionState.Timeout.TotalMinutes),
                AllowInsecureHttp = true
            });

            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
            {
                Provider = container.Resolve<IOAuthBearerAuthenticationProvider>(),
                //override the token deserialization to be able to capture the properties
                AccessTokenProvider = new AuthenticationTokenProvider()
                {
                    OnReceive = (c) =>
                    {
                        c.DeserializeTicket(c.Token);

                        //check if invalid bearer token received
                        if (c.Ticket != null)
                        {
                            c.OwinContext.Environment["oauth.Properties"] = c.Ticket.Properties;
                        }
                    }
                }
            });
        }
Example #26
0
        public void ConfigureOAuth(IAppBuilder app)
        {
            // Configure authentication
            // The object below represents options for authentication
            // The default options are good for now so we're not going to change anything
            var authenticationOptions = new OAuthBearerAuthenticationOptions();

            // Tell the app to use OAuthBearerAuthentication, passing in the authenticationOptions that we just instantiated
            app.UseOAuthBearerAuthentication(authenticationOptions);

            // Configure authorization
            // We do want to customize is how authorization works in our system
            // Same pattern as above, we're making options and then pass those options to the application
            var authorizationOptions = new OAuthAuthorizationServerOptions
            {
                // We are going to configure 4 properties here to customize authorization

                // We don't have https set up (secure set up)
                // So just for testing purposes, we're going to allow insecure http
                AllowInsecureHttp = true,

                // Because we're not writing a controller that accepts information (that's taken care of by ASP.Net.Identity)
                // We need to tell ASP.Net.Identity what route is; where is my user going to post to grab a token
                // We're telling it the endpoint path is a new path string and you have to hit /api/token to grab a token
                TokenEndpointPath = new PathString("/api/token"),

                // The token is only good for 1 day
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),

                // ASP.Net.Identity now wants to know where's the class that you wrote to intercept the events I'm going to throw at you
                Provider = new PropertyManagerAuthorizationServerProvider()
            };

            app.UseOAuthAuthorizationServer(authorizationOptions);
        }
        /// <summary>
        /// Se realiza la configuración de autorización
        /// </summary>
        /// <param name="app"></param>
        public void ConfigureOAuth(IAppBuilder app)
        {
            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                Provider = new SimpleAuthorizationServerProvider(),
                RefreshTokenProvider = new SimpleRefreshTokenProvider()
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
            app.UseExternalSignInCookie(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie);
            OAuthBearerOptions = new OAuthBearerAuthenticationOptions();

            googleAuthOptions = new GoogleOAuth2AuthenticationOptions()
            {
                ClientId = "185157178718-8qc15td8nefjssrai2md8eiodr151m8u.apps.googleusercontent.com",
                ClientSecret = "tmnYb6S99BJPWVbv45Ha8Mf-",
                Provider = new GoogleAuthProvider()
            };
            app.UseGoogleAuthentication(googleAuthOptions);

        }
Example #28
0
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();
            ConfigureFilters(app, config);
            ConfigureWebApi(app, config);

            var container = ConfigureDI(app, config);

            app.UseAutofacWebApi(config);
            app.UseAutofacMiddleware(container);

            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
            {
                Provider = container.Resolve<IOAuthBearerAuthenticationProvider>()
            });

            app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/api/auth/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(7),
                Provider = container.Resolve<IOAuthAuthorizationServerProvider>()
            });

            app.UseWebApi(config);
        }
Example #29
0
        public void ConfigureAuth(IAppBuilder app)
        {
            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AuthenticationType = Constant.GrantTypes.AuthenticationType,
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString(WebConfig.TokenPath),
                AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(int.Parse(WebConfig.AccessTokenExpireTimeSpan)),
                Provider = new OAuth2AuthorizationServerProvider(),
                RefreshTokenProvider = new OAuth2RefreshTokenProvider()
            };
            //AuthenticationType :认证类型
            //AllowInsecureHttp : 如果允许客户端的 return_uri 参数不是 HTTPS 地址, 则设置为 true
            //TokenEndpointPath : 客户端应用可以直接访问并得到访问令牌的地址, 必须以前倒斜杠 "/" 开始, 例如: /Token
            //AccessTokenExpireTimeSpan :Token过期时间
            //Provider : 应用程序提供和 OAuth 认证中间件交互的 IOAuthAuthorizationServerProvider 实例, 通常可以使用默认的
            //OAuthAuthorizationServerProvider , 并设置委托函数即可
            //RefreshTokenProvider :刷新令牌, 如果这个属性没有设置, 则不能从 /Token 刷新令牌

            // 令牌生成
            app.UseOAuthAuthorizationServer(OAuthServerOptions);

            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            //跨域处理
            app.UseCors(CorsOptions.AllowAll);
        }
Example #30
0
        private void ConfigureOAuth(IAppBuilder app)
        {
            //var serverOptions = new OAuthAuthorizationServerOptions()
            //{
            //    AuthenticationMode=Microsoft.Owin.Security.AuthenticationMode.Active,
            //    AllowInsecureHttp = true,
            //    TokenEndpointPath = new PathString("/token"),
            //    AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            //    Provider = new CIRAuthorizationServerProvider()
            //};
            //app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            var implicitGrantServerOptions = new OAuthAuthorizationServerOptions
            {
                AuthorizeEndpointPath= new PathString("/token"),
                Provider= new CIRImplicitAuthorizationServerProvider(),
                AllowInsecureHttp = true,
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(100)
            };

            app.UseOAuthAuthorizationServer(implicitGrantServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
            {
                AuthenticationType="Bearer",
                AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active
            });
        }
Example #31
0
        public void ConfigureOAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <MyUserManager>(MyUserManager.Create);

            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/api/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider          = new SimpleAuthorizationServerProvider(),
                AccessTokenFormat = new CustomJwtFormat()
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
            {
                AccessTokenFormat = new CustomJwtFormat()
            });
        }
Example #32
0
        void ConfigureOAuth(IAppBuilder app)
        {
            //Token üretimi için authorization ayarlarını belirliyoruz.
            OAuthAuthorizationServerOptions oAuthAuthorizationServerOptions = new OAuthAuthorizationServerOptions()
            {
                TokenEndpointPath         = new PathString("/token"), //Token talebini yapacağımız dizin
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),     //Oluşturulacak tokenı bir gün geçerli olacak şekilde ayarlıyoruz.
                AllowInsecureHttp         = true,                     //Güvensiz http portuna izin veriyoruz.
                Provider = new ProviderAuthorization()                //Sağlayıcı sınıfını belirtiyoruz. Birazdan bu sınıfı oluşturacağız.
            };

            //Yukarıda belirlemiş olduğumuz authorization ayarlarında çalışması için server'a ilgili OAuthAuthorizationServerOptions tipindeki nesneyi gönderiyoruz.
            app.UseOAuthAuthorizationServer(oAuthAuthorizationServerOptions);

            //Authentication Type olarak Bearer Authentication'ı kullanacağımızı belirtiyoruz.
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            //Bearer Token, OAuth 2.0 ile gelen standartlaşmış bir token türüdür.
            //Herhangi bir kriptolu veriye ihtiyaç duyulmaksızın client tarafından token isteğinde bulunulur ve server belirli bir zamana sahip access_token üretir.
            //Bearer Token SSL güvenliğine dayanır.
        }
Example #33
0
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            var myProvider = new AuthProvider();
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                Provider = myProvider
            };

            app.UseOAuthAuthorizationServer(options);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());


            HttpConfiguration config = new HttpConfiguration();

            WebApiConfig.Register(config);
        }
Example #34
0
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(() => new ApplicationIdentityDbContext());
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);
            app.CreatePerOwinContext <ApplicationRoleManager>(ApplicationRoleManager.Create);

            // Configure the application for OAuth based flow
            OAuthAuthorizationServerOptions oAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new AuthorizationServerProvider()
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(oAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
Example #35
0
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            var myProvider = new AppAuthorizationServiceProvider();
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = myProvider
            };

            app.UseOAuthAuthorizationServer(options);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            HttpConfiguration config = new HttpConfiguration();

            WebApiConfig.Register(config);
        }
Example #36
0
        public void Configuration(IAppBuilder app)
        {
            OAuthBearerOptions.AccessTokenFormat = new TicketDataFormat(app.CreateDataProtector(
                                                                            typeof(OAuthAuthorizationServerMiddleware).Namespace,
                                                                            "Access_Token", "v1"));

            app.UseOAuthBearerAuthentication(OAuthBearerOptions);
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            var OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath         = new PathString("/Token"),
                Provider                  = new OAuthAuthorizationServerProvider(),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),

                AllowInsecureHttp = true
            };

            app.UseOAuthAuthorizationServer(OAuthOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
Example #37
0
        private void ConfigureOAuthTokenGeneration(IAppBuilder app)
        {
            // Configure the db context and user manager to use a single instance per request
            app.CreatePerOwinContext(AppDbContext.Create);
            app.CreatePerOwinContext <AppUserManager>(AppUserManager.Create);

            // Plugin the OAuth bearer JSON Web Token tokens generation and Consumption will be here

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

            // OAuth 2.0 Bearer Access Token Generation
            app.UseOAuthAuthorizationServer(oAuthServerOptions);
        }
        private void ConfigureOAuthTokenGeneration(IAppBuilder app)
        {
            app.CreatePerOwinContext(WebSolutionDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationRoleManager>(ApplicationRoleManager.Create);

            int    accessTokenDuration = Convert.ToInt32(ConfigurationManager.AppSettings["AccessTokenDuration"]);
            string issuer = ConfigurationManager.AppSettings["IssuingUrl"];

            OAuthAuthorizationServerOptions oAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/api/oauth/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(accessTokenDuration),
                Provider             = new CustomOAuthProvider(),
                AccessTokenFormat    = new JwtToken(issuer),
                RefreshTokenProvider = new ApiRefreshTokenProvider()
            };

            app.UseOAuthAuthorizationServer(oAuthServerOptions);
        }
Example #39
0
        public void Configuration(IAppBuilder app)
        {
            // enable cros origine request
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            var authProvider = new AuthorizationServiceProvide();
            var options      = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = authProvider
            };

            app.UseOAuthAuthorizationServer(options);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            HttpConfiguration config = new HttpConfiguration();

            WebApiConfig.Register(config);
        }
Example #40
0
        public void ConfigureOAuth(IAppBuilder app)
        {
            //implemented from this example: https://stackoverflow.com/questions/25032513/how-to-get-error-message-returned-by-dotnetopenauth-oauth2-on-client-side
            app.Use <InvalidAuthenticationMiddleware>();

            //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);
            OAuthBearerOptions = new OAuthBearerAuthenticationOptions();

            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30000),
                Provider = new SimpleAuthorizationServerProvider(),
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(OAuthBearerOptions);
        }
Example #41
0
        public static void Install(HttpConfiguration config, IAppBuilder app)
        {
            WebApiUnityActionFilterProvider.RegisterFilterProviders(config);

            app.MapSignalR();


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

            app.UseCors(CorsOptions.AllowAll);

            config.SuppressHostPrincipal();

            IIdentityService          identityService       = UnityConfiguration.GetContainer().Resolve <IIdentityService>();
            Lazy <IAuthConfiguration> lazyAuthConfiguration = UnityConfiguration.GetContainer().Resolve <Lazy <IAuthConfiguration> >();

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

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

            app.UseJwtBearerAuthentication(new JwtOptions(lazyAuthConfiguration));

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

            var jSettings = new JsonSerializerSettings();

            jSettings.Formatting            = Formatting.Indented;
            jSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            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 }
                );
        }
Example #42
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(FleetManagementDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);

            // Configure the application for OAuth based flow
            PublicClientId = "self";
            OAuthOptions   = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath         = new PathString("/Token"),
                Provider                  = new ApplicationOAuthProvider(PublicClientId),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                // In production mode set AllowInsecureHttp = false
                AllowInsecureHttp = true
            };

            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthAuthorizationServer(OAuthOptions);
            app.UseOAuthBearerTokens(new OAuthAuthorizationServerOptions());

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //    consumerKey: "",
            //    consumerSecret: "");

            //app.UseFacebookAuthentication(
            //    appId: "",
            //    appSecret: "");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
Example #43
0
        /// <summary>
        /// Configuration of server of authorization
        /// </summary>
        /// <param name="app">Param of current context</param>
        public void ConfigureOAuth(IAppBuilder app)
        {
            blAUdience = new BlAudience();
            List <string> allowedAudienceIds = new List <string>();
            List <IIssuerSecurityTokenProvider> providers = new List <IIssuerSecurityTokenProvider>();

            var             issuer        = ConfigurationManager.AppSettings["issuer"];
            List <Audience> AudiencesList = blAUdience.GetAudiences();

            app.Use <BlAuthenticationMiddleware>(); //Allows override of Invoke OWIN commands ////El objetivo de esta petición es sobreescribir la petición para
            //// invocar el negocio BlAuthenticationMiddleware y retornar el codigo de no autorizado en la generación del token.

            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                //For Dev enviroment only (on production should be AllowInsecureHttp = false)
                AllowInsecureHttp         = bool.Parse(ConfigurationManager.AppSettings["allowInsecureHttp"]),
                TokenEndpointPath         = new PathString(ConfigurationManager.AppSettings["pathToken"]),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(Convert.ToInt16(ConfigurationManager.AppSettings["expiredToken"])),
                Provider          = new BlCustomOAuthProvider(),
                AccessTokenFormat = new BlCustomJwtFormat(issuer)
            };

            // OAuth 2.0 Bearer Access Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions); //// El objetivo de esta instrucción es configurar el servidor de autorización.

            foreach (var validAudience in AudiencesList)
            {
                allowedAudienceIds.Add(validAudience.ClientId);
                providers.Add(new SymmetricKeyIssuerSecurityTokenProvider(issuer, TextEncodings.Base64Url.Decode(validAudience.Secret)));
            }

            // Api controllers with an [Authorize] attribute will be validated with JWT
            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
            {
                AuthenticationMode           = AuthenticationMode.Active,
                AllowedAudiences             = allowedAudienceIds.ToArray(),
                IssuerSecurityTokenProviders = providers.ToArray()
            });
        }
Example #44
0
        public void ConfigureOAuth(IAppBuilder app, IAuthRepository authRepository)
        {
            //app.CreatePerOwinContext(ApplicationDbContext.Create);
            //app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

            //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);
            OAuthBearerOptions = new OAuthBearerAuthenticationOptions();

            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                Provider             = new SimpleAuthorizationServerProvider(authRepository),
                RefreshTokenProvider = new SimpleRefreshTokenProvider(authRepository)
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(OAuthBearerOptions);

            //Configure Google External Login
            googleAuthOptions = new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = "xxxxxx",
                ClientSecret = "xxxxxx",
                Provider     = new GoogleAuthProvider()
            };
            app.UseGoogleAuthentication(googleAuthOptions);

            ////Configure Facebook External Login
            //facebookAuthOptions = new FacebookAuthenticationOptions()
            //{
            //    AppId = "xxxxxx",
            //    AppSecret = "xxxxxx",
            //    Provider = new FacebookAuthProvider()
            //};
            //app.UseFacebookAuthentication(facebookAuthOptions);
        }
Example #45
0
        public void Configuration(IAppBuilder app)
        {
            app.Map("/signalr", map =>
            {
                map.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
                {
                    Provider = new QueryStringOAuthBearerProvider()
                });

                var hubConfiguration = new HubConfiguration
                {
                    EnableDetailedErrors = true,
                    Resolver             = GlobalHost.DependencyResolver,
                };
                map.RunSignalR(hubConfiguration);
            });
            //            var hubConfiguration = new HubConfiguration();
            //            hubConfiguration.EnableDetailedErrors = true;
            //
            //            app.MapSignalR(hubConfiguration);
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
            //enable cors origin requests
            //app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            var myProvider = new MyAuthorizationServerProvider();
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(7),
                Provider = myProvider
            };

            app.UseOAuthAuthorizationServer(options);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            HttpConfiguration config = new HttpConfiguration();

            WebApiConfig.Register(config);
        }
Example #46
0
        public void ConfigureAuth(IAppBuilder app)
        {
            // Enable Application Sign In Cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Application",
                AuthenticationMode = AuthenticationMode.Passive
            });

            // Setup Authorization Server
            app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
            {
                AuthorizeEndpointPath       = new PathString("/OAuth/Authorize"),
                TokenEndpointPath           = new PathString("/OAuth/Token"),
                ApplicationCanDisplayErrors = true,
#if DEBUG
                AllowInsecureHttp = true,
#endif
                // Authorization server provider which controls the lifecycle of Authorization Server
                Provider = new OAuthAuthorizationServerProvider
                {
                    OnValidateClientRedirectUri    = ValidateClientRedirectUri,
                    OnValidateClientAuthentication = ValidateClientAuthentication
                },

                // Authorization code provider which creates and receives authorization code
                AuthorizationCodeProvider = new AuthenticationTokenProvider
                {
                    OnCreate  = CreateAuthenticationCode,
                    OnReceive = ReceiveAuthenticationCode,
                },

                // Refresh token provider which creates and receives referesh token
                RefreshTokenProvider = new AuthenticationTokenProvider
                {
                    OnCreate  = CreateRefreshToken,
                    OnReceive = ReceiveRefreshToken,
                }
            });
        }
Example #47
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext(MyShopDbContext.Create);

            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationRoleManager>(ApplicationRoleManager.Create);
            app.CreatePerOwinContext <UserManager <AppUser> >(CreateManager);

            app.UseCors(CorsOptions.AllowAll);

            app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath         = new PathString("/api/oauth/token"),
                Provider                  = new AuthorizationServerProvider(),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                AllowInsecureHttp         = true
            });

            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            app.Map("/signalr", map =>
            {
                map.UseCors(CorsOptions.AllowAll);

                map.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
                {
                    Provider = new QueryStringOAuthBearerProvider()
                });

                var hubConfiguration = new HubConfiguration
                {
                    EnableJSONP          = true,
                    EnableDetailedErrors = true
                };
                map.RunSignalR(hubConfiguration);
            });
        }
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath         = new PathString("/Token"),
                Provider                  = new ApplicationOAuthProvider(PublicClientId),
                AuthorizeEndpointPath     = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                // In production mode set AllowInsecureHttp = false
                AllowInsecureHttp = true
            };

            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions);
            app.UseOAuthAuthorizationServer(OAuthOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            HttpConfiguration config = new HttpConfiguration();

            WebApiConfig.Register(config);
            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //    consumerKey: "",
            //    consumerSecret: "");

            //app.UseFacebookAuthentication(
            //    appId: "",
            //    appSecret: "");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
        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", "AspNetWebApi2MediatRCustomeElementsV1Starter"))
            .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 #50
0
        public void ConfigureOAuth(IAppBuilder app)
        {
            var tiempoExpiracionToken = Convert.ToDouble(ConfigurationManager.AppSettings["TiempoTokenHoras"]);

            var oAuthServerOptions = new OAuthAuthorizationServerOptions
            {
                AuthenticationType        = OAuthDefaults.AuthenticationType,
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/authorize"),
                AccessTokenExpireTimeSpan = TimeSpan.FromHours(tiempoExpiracionToken),
                Provider = new OAuthProvider()
            };

            var authOptions = new OAuthBearerAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Active
            };

            app.UseOAuthBearerAuthentication(authOptions);
            app.UseOAuthAuthorizationServer(oAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
Example #51
0
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
            //var cors = new EnableCorsAttribute("http://localhost:4200, ", "accept,accesstoken,authorization,cache-control,pragma,content-type,origin", "GET,PUT,POST,DELETE,TRACE,HEAD,OPTIONS");


            //  app.UseCors(CorsOptions.AllowAll);
            // app.UseCors(options => options.AllowAnyOrigin());

            OAuthAuthorizationServerOptions option = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath         = new PathString("/token"),
                Provider                  = new ApplicationOAuthProvider(),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),
                AllowInsecureHttp         = true
            };

            app.UseOAuthAuthorizationServer(option);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            //  var appSettings = WebConfigurationManager.AppSettings;
        }
Example #52
0
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(CorsOptions.AllowAll); //to enable cross origin

            var Myprovider = new MyAuthorizationServerProvider();


            var serverOptions = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = Myprovider
            };

            app.UseOAuthAuthorizationServer(serverOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            HttpConfiguration config = new HttpConfiguration();

            WebApiConfig.Register(config);
        }
Example #53
0
        public void Configuration(IAppBuilder app)
        {
            // Para obtener más información sobre cómo configurar la aplicación, visite https://go.microsoft.com/fwlink/?LinkID=316888

            app.UseCors(CorsOptions.AllowAll);
            ApplicationOAuthProvider        provider = new ApplicationOAuthProvider();
            OAuthAuthorizationServerOptions options  = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = provider
            };

            app.UseOAuthAuthorizationServer(options);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
            HttpConfiguration config = new HttpConfiguration();

            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

            WebApiConfig.Register(config);
        }
Example #54
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, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(EcommerceDbContext.Create);

            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationRoleManager>(ApplicationRoleManager.Create);
            app.CreatePerOwinContext <UserManager <AppUser> >(CreateManager);

            //Allow Cross origin for API
            app.UseCors(CorsOptions.AllowAll);

            // .NET API save to token
            app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath         = new PathString("/api/oauth/token"),
                Provider                  = new AuthorizationServerProvider(),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                AllowInsecureHttp         = true
            });
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            // .NET MVC save to cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/dang-nhap.html"),
                Provider           = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, AppUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager, DefaultAuthenticationTypes.ApplicationCookie)
                        )
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
        }
Example #55
0
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
            // token generation
            app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
            {
                // for demo purposes
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromHours(8),
                Provider             = new SimpleAuthorizationServerProvider(),
                RefreshTokenProvider = new SimpleRefreshTokenProvider()
            });
            app.UseCors(CorsOptions.AllowAll);

            // token consumption
            var config = new HttpConfiguration();

            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
            WebApiConfig.Register(config);
            app.UseWebApi(config);
        }
Example #56
0
        public static void ConfigureAuth0(IAppBuilder app)
        {
            var issuer          = ConfigurationManager.AppSettings["Auth0.Issuer"];
            var audience        = ConfigurationManager.AppSettings["Auth0.Audience"];
            var certificatePath = ConfigurationManager.AppSettings["Auth0.CertificatePath"];

            app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp   = true,
                TokenEndpointPath   = new PathString("/token"),
                Provider            = new Auth0AuthorizationServerProvider(),
                AccessTokenProvider = new Auth0AuthenticationTokenProvider()
            });

            var cert        = new X509Certificate2(certificatePath);
            var securityKey = new X509SecurityKey(cert);

            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
            {
                AuthenticationMode         = AuthenticationMode.Active,
                AllowedAudiences           = new[] { audience },
                IssuerSecurityKeyProviders = new IIssuerSecurityKeyProvider[]
                {
                    new X509CertificateSecurityKeyProvider(issuer, cert)
                },
                TokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKeyResolver = (arbitrarily, declaring, these, parameters) => new List <SecurityKey> {
                        securityKey
                    },
                    ValidAudience    = audience,
                    ValidateIssuer   = true,
                    ValidIssuer      = issuer,
                    IssuerSigningKey = securityKey
                }
            }
                );
        }
Example #57
0
        public void ConfigureOAuth(IAppBuilder app)
        {
            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                TokenEndpointPath = new PathString("/token"),
                Provider          = new QMAuthorizationServerProvider(),
                //AccessTokenProvider=new AccessTokenAuthorizationServerProvider(),
                //refresh token provider
                RefreshTokenProvider      = new QMRefreshTokenProvider(),
                AccessTokenExpireTimeSpan = new System.TimeSpan(0, 60, 0),
                AuthenticationMode        = AuthenticationMode.Active,
                //HTTPS is allowed only AllowInsecureHttp = false
#if DEBUG
                AllowInsecureHttp = true,
#endif
                ApplicationCanDisplayErrors = true,
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
Example #58
0
        public void ConfigureAuth(IAppBuilder app)
        {
            //this is very important line cross orgin source(CORS)it is used to enable cross-site HTTP requests
            //For security reasons, browsers restrict cross-origin HTTP requests
            app.UseCors(CorsOptions.AllowAll);

            var OAuthOptions = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),//token expiration time
                Provider = new OAuthProvider()
            };

            app.UseOAuthBearerTokens(OAuthOptions);
            app.UseOAuthAuthorizationServer(OAuthOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            HttpConfiguration config = new HttpConfiguration();

            WebApiConfig.Register(config);//register the request
        }
Example #59
0
        private void ConfigureOAuthTokenGeneration(IAppBuilder app)
        {
            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            //app.UseCookieAuthentication(new CookieAuthenticationOptions());
            //app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Configure the application for OAuth based flow
            var oAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                TokenEndpointPath         = new PathString("/auth/login"),
                AccessTokenExpireTimeSpan = TimeSpan.FromHours(12),
                Provider             = new CustomOAuthProvider(),
                AccessTokenFormat    = new CustomJwtFormat(_issuer, _audienceId, _audienceSecret),
                RefreshTokenProvider = new TokenRefreshProvider(),
                //For Dev enviroment only (on production should be AllowInsecureHttp = false)
                AllowInsecureHttp = true
            };

            // OAuth 2.0 Bearer Access Token Generation
            app.UseOAuthAuthorizationServer(oAuthServerOptions);
        }
Example #60
0
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                //The Path For generating the Toekn
                TokenEndpointPath = new PathString("/token"),
                //Setting the Token Expired Time (24 hours)
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                //MyAuthorizationServerProvider class will validate the user credentials
                Provider = new CustomAuthorizationServiceProvider()
            };

            app.UseOAuthAuthorizationServer(options);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            HttpConfiguration config = new HttpConfiguration();

            WebApiConfig.Register(config);
        }