Пример #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);
        }
Пример #2
1
        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);
        }
Пример #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);
        }
Пример #4
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 Google External Login
            googleAuthOptions = new GoogleOAuth2AuthenticationOptions()
            {
                ClientId = "xxxxxx",
                ClientSecret = "xxxxxx",
                Provider = new GoogleAuthProvider()
            };
            app.UseGoogleAuthentication(googleAuthOptions);

            //Configure Facebook External Login
            facebookAuthOptions = new FacebookAuthenticationOptions()
            {
                AppId = System.Configuration.ConfigurationManager.AppSettings["FacebookAppId"],
                AppSecret = System.Configuration.ConfigurationManager.AppSettings["FacebookAppSecret"],
                Provider = new FacebookAuthProvider()
            };
            app.UseFacebookAuthentication(facebookAuthOptions);

            //Configure Twitter External Login
           twitterAuthOptions = new TwitterAuthenticationOptions()
            {
                ConsumerKey = System.Configuration.ConfigurationManager.AppSettings["TwitterConsumerKey"],
                ConsumerSecret = System.Configuration.ConfigurationManager.AppSettings["TwitterConsumerSecret"],
                Provider = new TwitterAuthProvider()
            };
           app.UseTwitterAuthentication(twitterAuthOptions);

           //Configure LinkedIn External Login
           linkedinAuthOptions = new LinkedInAuthenticationOptions()
           {

               ClientId = System.Configuration.ConfigurationManager.AppSettings["LinkedInClientId"],
               ClientSecret = System.Configuration.ConfigurationManager.AppSettings["LinkedInSecret"],
               Provider = new LinkedInAuthProvider()
           };
           app.UseLinkedInAuthentication(linkedinAuthOptions);

           

        }
        /// <summary>
        /// Adds Windows Azure Active Directory (WAAD) issued JWT bearer token middleware to your web application pipeline.
        /// </summary>
        /// <param name="app">The IAppBuilder passed to your configuration method.</param>
        /// <param name="options">An options class that controls the middleware behavior.</param>
        /// <returns>The original app parameter.</returns>
        public static IAppBuilder UseWindowsAzureActiveDirectoryBearerAuthentication(this IAppBuilder app, WindowsAzureActiveDirectoryBearerAuthenticationOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            if (string.IsNullOrWhiteSpace(options.Tenant))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.Exception_OptionMustBeProvided, "Tenant"));
            }

            var bearerOptions = new OAuthBearerAuthenticationOptions
            {
                Realm = options.Realm,
                Provider = options.Provider,
                AccessTokenFormat = new JwtFormat(options.Audience,
                    new WsFedCachingSecurityTokenProvider(
                        string.Format(CultureInfo.InvariantCulture, SecurityTokenServiceAddressFormat, options.Tenant),
                        options.BackchannelCertificateValidator, options.BackchannelTimeout, options.BackchannelHttpHandler)),
                AuthenticationMode = options.AuthenticationMode,
                AuthenticationType = options.AuthenticationType,
                Description = options.Description
            };

            app.UseOAuthBearerAuthentication(bearerOptions);

            return app;
        }
Пример #6
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();
        }
        public void Configuration(IAppBuilder app)
        {
            // token generation
            var serverOptions = new OAuthAuthorizationServerOptions
            {
                // for demo purposes
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromHours(8),
                Provider = new SimpleAuthorizationServerProvider(),
                AuthenticationMode = AuthenticationMode.Active,
                AuthenticationType = "Bearer"
            };
#if Debug
            System.Diagnostics.Debugger.Launch();
#endif
            app.UseOAuthAuthorizationServer(serverOptions); // Adds OAuth2 Authorization Server capabilities to an OWIN web application.
            /*  
            This middleware performs the request processing for the Authorize and Token endpoints defined by the OAuth2 specification. 
            See also http://tools.ietf.org/html/rfc6749
            */
            // token consumption
            var bearerOptions = new OAuthBearerAuthenticationOptions();
            app.UseOAuthBearerAuthentication(bearerOptions); // Adds Bearer token processing to an OWIN application pipeline. 
            /* 
            This middleware understands appropriately formatted and 
            secured tokens which appear in the request header. If the Options.AuthenticationMode is Active, the claims within the 
            bearer token are added to the current request's IPrincipal User. 
            See also http://tools.ietf.org/html/rfc6749 
            */
            app.UseWebApi(WebApiConfig.Register()); // add WebAPI endpoint processing to OWIN pipeline
        }
Пример #8
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);
        }
Пример #9
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);

        }
Пример #10
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);
        }
Пример #11
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()});
        }
Пример #12
0
        /// <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);

        }
        /// <summary>
        /// Adds JWT bearer token middleware to your web application pipeline.
        /// </summary>
        /// <param name="app">The IAppBuilder passed to your configuration method.</param>
        /// <param name="options">An options class that controls the middleware behavior.</param>
        /// <returns>The original app parameter.</returns>
        public static IAppBuilder UseJwtBearerAuthentication(this IAppBuilder app, JwtBearerAuthenticationOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException("app");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            var bearerOptions = new OAuthBearerAuthenticationOptions
            {
                Realm = options.Realm,
                Provider = options.Provider,
                AccessTokenFormat = new JwtFormat(options.AllowedAudiences, options.IssuerSecurityTokenProviders),
                AuthenticationMode = options.AuthenticationMode,
                AuthenticationType = options.AuthenticationType,
                Description = options.Description
            };

            app.UseOAuthBearerAuthentication(bearerOptions);

            return app;
        }
Пример #14
0
        public void Configuration(IAppBuilder app)
        {
            ConfigureMembershipReboot(app);

            var oauthServerConfig = new Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                Provider          = new MyProvider(),
                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();

            config.MapHttpAttributeRoutes();
            app.UseWebApi(config);
        }
Пример #15
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);
        }
Пример #16
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);
        }
Пример #17
0
        public void ConfigureAuth(IAppBuilder app)
        {
            var options = new OAuthBearerAuthenticationOptions()
                          {
                              AccessTokenFormat = new TicketDataFormat()
                          };

            app.UseOAuthBearerAuthentication(options);
        }
Пример #18
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            //            //use a cookie to temporarily store information about a user logging in with a third party login provider
            //            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
            OAuthBearerOptions = new OAuthBearerAuthenticationOptions();

            // Token Generation
            app.UseOAuthBearerTokens(OAuthServerOptions);
        }
        /// <summary>
        /// Adds Active Directory Federation Services (ADFS) issued JWT bearer token middleware to your web application pipeline.
        /// </summary>
        /// <param name="app">The IAppBuilder passed to your configuration method.</param>
        /// <param name="options">An options class that controls the middleware behavior.</param>
        /// <returns>The original app parameter.</returns>
        public static IAppBuilder UseActiveDirectoryFederationServicesBearerAuthentication(this IAppBuilder app, ActiveDirectoryFederationServicesBearerAuthenticationOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            var cachingSecurityTokenProvider = new WsFedCachingSecurityTokenProvider(options.MetadataEndpoint,
                    options.BackchannelCertificateValidator, options.BackchannelTimeout, options.BackchannelHttpHandler);

#pragma warning disable 618
            JwtFormat jwtFormat = null;
            if (options.TokenValidationParameters != null)
            {
                if (!string.IsNullOrWhiteSpace(options.Audience))
                {
                    // Carry over obsolete property if set
                    if (string.IsNullOrWhiteSpace(options.TokenValidationParameters.ValidAudience))
                    {
                        options.TokenValidationParameters.ValidAudience = options.Audience;
                    }
                    else if (options.TokenValidationParameters.ValidAudiences == null)
                    {
                        options.TokenValidationParameters.ValidAudiences = new[] { options.Audience };
                    }
                    else
                    {
                        options.TokenValidationParameters.ValidAudiences = options.TokenValidationParameters.ValidAudiences.Concat(new[] { options.Audience });
                    }
                }

                jwtFormat = new JwtFormat(options.TokenValidationParameters, cachingSecurityTokenProvider);
            }
            else
            {
                jwtFormat = new JwtFormat(options.Audience, cachingSecurityTokenProvider);
            }
#pragma warning restore 618
            if (options.TokenHandler != null)
            {
                jwtFormat.TokenHandler = options.TokenHandler;
            }

            var bearerOptions = new OAuthBearerAuthenticationOptions
            {
                Realm = options.Realm,
                Provider = options.Provider,
                AccessTokenFormat = jwtFormat,
                AuthenticationMode = options.AuthenticationMode,
                AuthenticationType = options.AuthenticationType,
                Description = options.Description
            };

            app.UseOAuthBearerAuthentication(bearerOptions);

            return app;
        }
Пример #20
0
        public static void ConfigureAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext(ApplicationDbContext.Create);

            OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
            //Token Consumption
            app.UseOAuthBearerAuthentication(OAuthBearerOptions);

        }
Пример #21
0
        //public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
        //public static Func<UserManager<ApplicationUser>> UserManagerFactory { get; set; }
        //public static string PublicClientId { get; private set; }
        public void Configuration(IAppBuilder app)
        {
            //var idProvider = new CustomUserIdProvider();
            //GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => idProvider);

            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            //  PublicClientId = "self";

            //OAuthOptions = new OAuthAuthorizationServerOptions
            //{
            //    //TokenEndpointPath = new PathString("/Token"),
            //    Provider = new ApplicationOAuthProvider(PublicClientId),
            //    //AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            //    AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            //    #if DEBUG
            //    AllowInsecureHttp = true
            //    #endif
            //};

            OAuthBearerOptions = new OAuthBearerAuthenticationOptions()
            {
                //AccessTokenFormat = OAuthOptions.AccessTokenFormat,
                //AccessTokenProvider = OAuthOptions.AccessTokenProvider,
                //AuthenticationMode = OAuthOptions.AuthenticationMode,
                //AuthenticationType = OAuthOptions.AuthenticationType,
                //Description = OAuthOptions.Description,
                Provider = new CustomBearerAuthenticationProvider(),
                //SystemClock = OAuthOptions.SystemClock
            };
            OAuthBearerAuthenticationExtensions.UseOAuthBearerAuthentication(app, OAuthBearerOptions);

            app.Map("/signalr", map =>
            {
                // Setup the CORS middleware to run before SignalR.
                // By default this will allow all origins. You can
                // configure the set of origins and/or http verbs by
                // providing a cors options with a different policy.
                map.UseCors(CorsOptions.AllowAll);
                var hubConfiguration = new HubConfiguration
                {
                    // You can enable JSONP by uncommenting line below.
                    // JSONP requests are insecure but some older browsers (and some
                    // versions of IE) require JSONP to work cross domain
                    // EnableJSONP = true
                };
                // Run the SignalR pipeline. We're not using MapSignalR
                // since this branch already runs under the "/signalr"
                // path.
                map.RunSignalR(hubConfiguration);
            });
            //app.MapSignalR();
        }
Пример #22
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        /// <summary>
        /// 
        /// </summary>
        /// <param name="app"></param>
        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);

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

            var oAuthServerOptions = new OAuthAuthorizationServerOptions()
            {

                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/api/login"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                Provider = new ApplicationOAuthProvider(),
                RefreshTokenProvider = new RefreshTokenProvider()
            };

            app.Use(async (context, next) =>
            {
                var req = context.Request;
                var res = context.Response;
                // for auth2 token requests
                if (req.Path.StartsWithSegments(new PathString("/api/login")))
                {
                    // if there is an origin header
                    var origin = req.Headers.Get("Origin");
                    if (!string.IsNullOrEmpty(origin))
                    {
                        // allow the cross-site request
                        res.Headers.Set("Access-Control-Allow-Origin", origin);
                    }

                    // if this is pre-flight request
                    if (req.Method == "OPTIONS")
                    {
                        // respond immediately with allowed request methods and headers
                        res.StatusCode = 200;
                        res.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Methods", "GET", "POST");
                        res.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Headers", "authorization", "content-type");
                        // no further processing
                        return;
                    }
                }
                // continue executing pipeline
                await next();
            });

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

        }
Пример #23
0
        public void ConfigureAuth(IAppBuilder app)
        {
            OAuthBearerOptions = new OAuthBearerAuthenticationOptions();

            app.UseOAuthBearerAuthentication(OAuthBearerOptions);
            //app.UseCookieAuthentication(new CookieAuthenticationOptions
            //{
            //    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            //    LoginPath = new PathString("/#signin")
            //});
        }
        /// <summary>
        /// Adds Bearer token processing to an OWIN application pipeline. This middleware understands appropriately
        /// formatted and secured tokens which appear in the request header. If the Options.AuthenticationMode is Active, the
        /// claims within the bearer token are added to the current request's IPrincipal User. If the Options.AuthenticationMode 
        /// is Passive, then the current request is not modified, but IAuthenticationManager AuthenticateAsync may be used at
        /// any time to obtain the claims from the request's bearer token.
        /// See also http://tools.ietf.org/html/rfc6749
        /// </summary>
        /// <param name="app">The web application builder</param>
        /// <param name="options">Options which control the processing of the bearer header.</param>
        /// <returns>The application builder</returns>
        public static IAppBuilder UseOAuthBearerAuthentication(this IAppBuilder app, OAuthBearerAuthenticationOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException("app");
            }

            app.Use(typeof(OAuthBearerAuthenticationMiddleware), app, options);
            app.UseStageMarker(PipelineStage.Authenticate);
            return app;
        }
        public static IAppBuilder UseTokenHandlerAuthentication(this IAppBuilder app, SecurityTokenHandler handler)
        {
            var options = new OAuthBearerAuthenticationOptions
            {
                AccessTokenFormat = new WifTokenFormat(handler)
            };

            app.UseOAuthBearerAuthentication(options);

            return app;
        }
Пример #26
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.UseOAuthAuthorizationServer(OAuthOptions);

            var OAuthBearerOptions = new OAuthBearerAuthenticationOptions
            {
                Provider = new OAuthBearerAuthenticationProvider
                {
                    OnRequestToken = context => { return Task.FromResult<object>(null); }
                }
            };
            app.UseOAuthBearerAuthentication(OAuthBearerOptions);
        }
Пример #27
0
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration httpConfig = new HttpConfiguration();

            OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
            app.UseOAuthBearerAuthentication(OAuthBearerOptions);
            
            ConfigureOAuthTokenGeneration(app);
            ConfigureOAuthTokenConsumption(app);
            ConfigureWebApi(httpConfig);
            app.UseCors(CorsOptions.AllowAll);
            app.UseWebApi(httpConfig);
        }
Пример #28
0
            public static void Configure(IAppBuilder app)
            {
                var authFunc =
                    new Func<OAuthGrantResourceOwnerCredentialsContext, Task<Security.UserAuthenticationResult>>((c) =>
                    {
                        var task = new Task<Security.UserAuthenticationResult>(() =>
                        {

                            using (var context = new SampleDbContext())
                            {
                                var user =
                                    context.SystemUsers.FirstOrDefault(
                                        u => u.Id == c.UserName && u.Password == c.Password);

                                if (user != null)
                                {
                                    var roles = user.Roles.ToArray();
                                    return Security.UserAuthenticationResult.CreateAuthorizedResult(user, roles);
                                }

                                return Security.UserAuthenticationResult.CreateErrorResult("Invalid credentials");
                            }

                        });

                        task.Start();
                        return task;
                    });

                var authServerOptions = new OAuthAuthorizationServerOptions()
                {
                    AllowInsecureHttp = true,
                    TokenEndpointPath = new PathString("/token"),
                    AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                    Provider = new Security.BasicOAuthAuthorizationProvider(authFunc),
                    AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
                    AuthenticationType = "Bearer"
                };

                var bearerAuthOptions = new OAuthBearerAuthenticationOptions()
                {
                    AuthenticationType = authServerOptions.AuthenticationType,
                    AuthenticationMode = authServerOptions.AuthenticationMode,
                    AccessTokenFormat = authServerOptions.AccessTokenFormat,
                    AccessTokenProvider = authServerOptions.AccessTokenProvider,
                };

                // Token Generation
                app.UseOAuthAuthorizationServer(authServerOptions);
                app.UseOAuthBearerAuthentication(bearerAuthOptions);
            }
Пример #29
0
        public void Configuration(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();

            HttpConfiguration config = new HttpConfiguration();

            ConfigureOAuth(app);

            WebApiConfig.Register(config);
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.UseWebApi(config);
        }
Пример #30
0
        public void ConfigureOAuth(IAppBuilder app)
        {
            var authenticationOptions = new OAuthBearerAuthenticationOptions();
            app.UseOAuthBearerAuthentication(authenticationOptions);

            var authorizationOptions = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/api/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new PropertyManagerAuthorizationServerProvider()
            };
            app.UseOAuthAuthorizationServer(authorizationOptions);
        }
        public static IAppBuilder UseWindowsAzureBearerToken(this IAppBuilder app, WindowsAzureJwtBearerAuthenticationOptions options)
        {
            var bearerOptions = new OAuthBearerAuthenticationOptions
            {
                Realm = options.Realm, 
                Provider = options.Provider, 
                AccessTokenHandler = new WindowsAzureJwtTokenHandler(options.Tenant, options.Audience, options.MetadataResolver), 
                AuthenticationMode = options.AuthenticationMode, 
                AuthenticationType = options.AuthenticationType, 
                Description = options.Description
            };

            app.UseOAuthBearerAuthentication(bearerOptions);

            return app;
        }