Esempio n. 1
0
		// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
		public void ConfigureAuth(IAppBuilder app)
		{
			// Enable the application to use a cookie to store information for the signed in user
			app.UseCookieAuthentication(new CookieAuthenticationOptions
			{
				AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
				LoginPath = new PathString("/Account/Login")
			});
			// Use a cookie to temporarily store information about a user logging in with a third party login provider
			app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

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


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

			app.UseVkAuthentication(
				appId: "4381546",
				appSecret: "rqrWfJMYUT6Y3io91B3B");

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

//			app.UseGoogleAuthentication();
			app.UseLtiAuthentication();
		}
Esempio n. 2
0
        public static IAppBuilder UseLtiAuthentication(this IAppBuilder app)
        {
            app.UseLtiAuthentication(new LtiAuthenticationOptions
            {
                Provider = new LtiAuthenticationProvider
                {
                    // Look up the secret for the consumer
                    OnAuthenticate = async context =>
                    {
                        // Make sure the request is not being replayed
                        var timeout = TimeSpan.FromMinutes(5);
                        var oauthTimestampAbsolute = OAuthConstants.Epoch.AddSeconds(context.LtiRequest.Timestamp);
                        if (DateTime.UtcNow - oauthTimestampAbsolute > timeout)
                        {
                            log.Error($"Неправильное время у LTI-запроса: {context.LtiRequest.Timestamp}, сейчас {DateTime.UtcNow}, прошло больше 5 минут");
                            throw new LtiException("Expired " + OAuthConstants.TimestampParameter);
                        }

                        var db       = new ULearnDb();
                        var consumer = await db.Consumers.SingleOrDefaultAsync(c => c.Key == context.LtiRequest.ConsumerKey);
                        if (consumer == null)
                        {
                            throw new LtiException("Invalid " + OAuthConstants.ConsumerKeyParameter + " " + context.LtiRequest.ConsumerKey);
                        }

                        /* Substitute http(s) scheme with real scheme from header */
                        var uriBuilder = new UriBuilder(context.LtiRequest.Url)
                        {
                            Scheme = context.OwinContext.Request.GetRealRequestScheme(),
                            Port   = context.OwinContext.Request.GetRealRequestPort()
                        };
                        context.LtiRequest.Url = uriBuilder.Uri;

                        var signature = context.LtiRequest.GenerateSignature(consumer.Secret);
                        if (!signature.Equals(context.LtiRequest.Signature))
                        {
                            throw new LtiException("Invalid " + OAuthConstants.SignatureParameter);
                        }

                        // If we made it this far the request is valid
                    },

                    // Sign in using application authentication. This handler will create a new application
                    // user if no matching application user is found.
                    OnAuthenticated = context => SecurityHandler.OnAuthenticated(context),

                    // Generate a username using the LisPersonEmailPrimary from the LTI request
                    OnGenerateUserName = context => SecurityHandler.OnGenerateUserName(context)
                },
                //SignInAsAuthenticationType = DefaultAuthenticationTypes.ApplicationCookie
                SignInAsAuthenticationType = "Identity.Application"
            });

            return(app);
        }
Esempio n. 3
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(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.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
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
//                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
//                     Enables the application to validate the security stamp when the user logs in.
//                     This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
//            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
//            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
//            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

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

            app.UseLtiAuthentication();
        }
Esempio n. 4
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(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.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
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
//                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
//                     Enables the application to validate the security stamp when the user logs in.
//                     This is a security feature which is used when you change a password or add an external login to your account.  
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });            
//            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
//            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
//            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

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

	        app.UseLtiAuthentication();
        }
        public static IAppBuilder UseLtiAuthentication(this IAppBuilder app)
        {
            app.UseLtiAuthentication(new LtiAuthenticationOptions
            {
                Provider = new LtiAuthenticationProvider
                {
                    // Look up the secret for the consumer
                    OnAuthenticate = async context =>
                    {
                        // Make sure the request is not being replayed
                        var timeout = TimeSpan.FromMinutes(5);
                        var oauthTimestampAbsolute = OAuthConstants.Epoch.AddSeconds(context.LtiRequest.Timestamp);
                        if (DateTime.UtcNow - oauthTimestampAbsolute > timeout)
                        {
                            throw new LtiException("Expired " + OAuthConstants.TimestampParameter);
                        }

                        var db       = new ULearnDb();
                        var consumer = await db.Consumers.SingleOrDefaultAsync(c => c.Key == context.LtiRequest.ConsumerKey);
                        if (consumer == null)
                        {
                            throw new LtiException("Invalid " + OAuthConstants.ConsumerKeyParameter + " " + context.LtiRequest.ConsumerKey);
                        }

                        var signature = context.LtiRequest.GenerateSignature(consumer.Secret);
                        if (!signature.Equals(context.LtiRequest.Signature))
                        {
                            throw new LtiException("Invalid " + OAuthConstants.SignatureParameter);
                        }

                        // If we made it this far the request is valid
                    },

                    // Sign in using application authentication. This handler will create a new application
                    // user if no matching application user is found.
                    OnAuthenticated = context => SecurityHandler.OnAuthenticated(context),

                    // Generate a username using the LisPersonEmailPrimary from the LTI request
                    OnGenerateUserName = context => SecurityHandler.OnGenerateUserName(context)
                },
                SignInAsAuthenticationType = DefaultAuthenticationTypes.ApplicationCookie
            });

            return(app);
        }
Esempio n. 6
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext(() => new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new ULearnDb())));

            // Enable the application to use a cookie to store information for the signed in user
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <UserManager <ApplicationUser>, ApplicationUser, String>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
                        getUserIdCallback: identity => identity.GetUserId()
                        )
                }
            });
            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

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


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

            app.UseVkAuthentication(
                appId: "4381546",
                appSecret: "rqrWfJMYUT6Y3io91B3B");

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

//			app.UseGoogleAuthentication();
            app.UseLtiAuthentication();
        }
Esempio n. 7
0
		// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
		public void ConfigureAuth(IAppBuilder app)
		{
			app.CreatePerOwinContext(() => new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ULearnDb())));

			// Enable the application to use a cookie to store information for the signed in user
			app.UseCookieAuthentication(new CookieAuthenticationOptions
			{
				AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
				LoginPath = new PathString("/Login"),
				Provider = new CookieAuthenticationProvider
				{
					OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<UserManager<ApplicationUser>, ApplicationUser, String>(
						validateInterval: TimeSpan.FromMinutes(30),
						regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
						getUserIdCallback: identity => identity.GetUserId()
					)
				}
			});
			// Use a cookie to temporarily store information about a user logging in with a third party login provider
			app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

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


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

			app.UseVkAuthentication(
				appId: "4381546",
				appSecret: "rqrWfJMYUT6Y3io91B3B");

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

//			app.UseGoogleAuthentication();
			app.UseLtiAuthentication();
		}
Esempio n. 8
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext(() => new ULearnUserManager(new ULearnDb()));

            var configuration = ApplicationConfiguration.Read <WebApiConfiguration>();

            // Enable the application to use a cookie to store information for the signed in user
            var cookieKeyRingDirectory = new DirectoryInfo(Path.Combine(Utils.GetAppPath(), configuration.Web.CookieKeyRingDirectory));

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Identity.Application",
                CookieName         = configuration.Web.CookieName,
                CookieDomain       = configuration.Web.CookieDomain,
                CookieSameSite     = configuration.Web.CookieSecure ? SameSiteMode.None : SameSiteMode.Lax,                                                                    // https://docs.microsoft.com/ru-ru/aspnet/samesite/system-web-samesite
                CookieManager      = configuration.Web.CookieSecure ? new SameSiteCookieManager(new SystemWebCookieManager()) : (ICookieManager) new SystemWebCookieManager(), // https://docs.microsoft.com/ru-ru/aspnet/samesite/csmvc
                CookieSecure       = configuration.Web.CookieSecure ? CookieSecureOption.Always : CookieSecureOption.Never,

                LoginPath = new PathString("/Login"),
                Provider  = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ULearnUserManager, ApplicationUser, string>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
                        getUserIdCallback: identity => identity.GetUserId()
                        )
                },

                /* Configure sharing cookies between application.
                 * See https://docs.microsoft.com/en-us/aspnet/core/security/cookie-sharing?tabs=aspnetcore2x for details */
                TicketDataFormat = new AspNetTicketDataFormat(
                    new DataProtectorShim(
                        DataProtectionProvider.Create(cookieKeyRingDirectory, builder => builder.SetApplicationName("ulearn"))
                        .CreateProtector(
                            "Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware",
                            "Identity.Application",
                            // DefaultAuthenticationTypes.ApplicationCookie,
                            "v2"))),
            });

            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

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

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

            var vkAppId     = WebConfigurationManager.AppSettings["owin.vk.appId"];
            var vkAppSecret = WebConfigurationManager.AppSettings["owin.vk.appSecret"];

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

            var konturPassportClientId = WebConfigurationManager.AppSettings["owin.konturPassport.clientId"];

            if (!string.IsNullOrEmpty(konturPassportClientId))
            {
                app.UseKonturPassportAuthentication(konturPassportClientId);
            }

            //app.UseGoogleAuthentication();
            app.UseLtiAuthentication();
        }
Esempio n. 9
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(ConsumerContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);
            // The app also uses a RoleManager
            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
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                CookieName         = ".Consumer.AspNet.Cookies",
                LoginPath          = new PathString("/Account/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

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

            app.UseLtiAuthentication(new LtiAuthenticationOptions
            {
                Provider = new LtiAuthenticationProvider
                {
                    // Look up the secret for the consumer
                    OnAuthenticate = async context =>
                    {
                        // Make sure the request is not being replayed
                        var timeout = TimeSpan.FromMinutes(5);
                        var oauthTimestampAbsolute = OAuthConstants.Epoch.AddSeconds(context.LtiRequest.Timestamp);
                        if (DateTime.UtcNow - oauthTimestampAbsolute > timeout)
                        {
                            throw new LtiException("Expired " + OAuthConstants.TimestampParameter);
                        }

                        var db       = context.OwinContext.Get <ConsumerContext>();
                        var consumer = await db.ContentItemTools.SingleOrDefaultAsync(c => c.ConsumerKey == context.LtiRequest.ConsumerKey);
                        if (consumer == null)
                        {
                            throw new LtiException("Invalid " + OAuthConstants.ConsumerKeyParameter);
                        }

                        var signature = context.LtiRequest.GenerateSignature(consumer.ConsumerSecret);
                        if (!signature.Equals(context.LtiRequest.Signature))
                        {
                            throw new LtiException("Invalid " + OAuthConstants.SignatureParameter);
                        }

                        // If we made it this far the request is valid
                    },
                },

                // Default application signin
                SignInAsAuthenticationType = DefaultAuthenticationTypes.ApplicationCookie
            });
        }
Esempio n. 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, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ConsumerContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
            // The app also uses a RoleManager
            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
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                CookieName = ".Consumer.AspNet.Cookies",
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.  
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

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

            app.UseLtiAuthentication(new LtiAuthenticationOptions
            {
                Provider = new LtiAuthenticationProvider
                {
                    // Look up the secret for the consumer
                    OnAuthenticate = async context =>
                    {
                        // Make sure the request is not being replayed
                        var timeout = TimeSpan.FromMinutes(5);
                        var oauthTimestampAbsolute = OAuthConstants.Epoch.AddSeconds(context.LtiRequest.Timestamp);
                        if (DateTime.UtcNow - oauthTimestampAbsolute > timeout)
                        {
                            throw new LtiException("Expired " + OAuthConstants.TimestampParameter);
                        }

                        var db = context.OwinContext.Get<ConsumerContext>();
                        var consumer = await db.ContentItemTools.SingleOrDefaultAsync(c => c.ConsumerKey == context.LtiRequest.ConsumerKey);
                        if (consumer == null)
                        {
                            throw new LtiException("Invalid " + OAuthConstants.ConsumerKeyParameter);
                        }

                        var signature = context.LtiRequest.GenerateSignature(consumer.ConsumerSecret);
                        if (!signature.Equals(context.LtiRequest.Signature))
                        {
                            throw new LtiException("Invalid " + OAuthConstants.SignatureParameter);
                        }

                        // If we made it this far the request is valid
                    },
                },

                // Default application signin
                SignInAsAuthenticationType = DefaultAuthenticationTypes.ApplicationCookie
            });

        }
Esempio n. 11
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(ProviderContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
            // The app also uses a RoleManager
            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
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                CookieName = ".Provider.AspNet.Cookies",
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.  
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

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


            app.UseLtiAuthentication(new LtiAuthenticationOptions
            {
                Provider = new LtiAuthenticationProvider
                {
                    // Look up the secret for the consumer
                    OnAuthenticate = async context =>
                    {
                        // Make sure the request is not being replayed
                        var timeout = TimeSpan.FromMinutes(5);
                        var oauthTimestampAbsolute = OAuthConstants.Epoch.AddSeconds(context.LtiRequest.Timestamp);
                        if (DateTime.UtcNow - oauthTimestampAbsolute > timeout)
                        {
                            throw new LtiException("Expired " + OAuthConstants.TimestampParameter);
                        }

                        var db = context.OwinContext.Get<ProviderContext>();
                        var consumer = await db.Consumers.SingleOrDefaultAsync(c => c.Key == context.LtiRequest.ConsumerKey);
                        if (consumer == null)
                        {
                            throw new LtiException("Invalid " + OAuthConstants.ConsumerKeyParameter);
                        }

                        var signature = context.LtiRequest.GenerateSignature(consumer.Secret);
                        if (!signature.Equals(context.LtiRequest.Signature))
                        {
                            throw new LtiException("Invalid " + OAuthConstants.SignatureParameter);
                        }

                        // If we made it this far the request is valid
                    },

                    // Sign in using application authentication. This handler will create a new application
                    // user if no matching application user is found.
                    OnAuthenticated = async context =>
                    {
                        var db = context.OwinContext.Get<ProviderContext>();
                        var consumer = await db.Consumers.SingleOrDefaultAsync(c => c.Key.Equals(context.LtiRequest.ConsumerKey));
                        if (consumer == null) return;

                        // Record the request for logging purposes and as reference for outcomes
                        var providerRequest = new ProviderRequest
                        {
                            Received = DateTime.UtcNow,
                            LtiRequest = JsonConvert.SerializeObject(context.LtiRequest, Formatting.None, 
                            new JsonSerializerSettings {  NullValueHandling = NullValueHandling.Ignore })
                        };
                        db.ProviderRequests.Add(providerRequest);
                        db.SaveChanges();

                        // Add the requst ID as a claim
                        var claims = new List<Claim>
                        {
                            new Claim("ProviderRequestId",
                                providerRequest.ProviderRequestId.ToString(CultureInfo.InvariantCulture))
                        };

                        // Outcomes can live a long time to give the teacher enough
                        // time to grade the assignment. So they are stored in a separate table.
                        var lisOutcomeServiceUrl = ((IOutcomesManagementRequest) context.LtiRequest).LisOutcomeServiceUrl;
                        var lisResultSourcedid = ((IOutcomesManagementRequest)context.LtiRequest).LisResultSourcedId;
                        if (!string.IsNullOrWhiteSpace(lisOutcomeServiceUrl)
                            && !string.IsNullOrWhiteSpace(lisResultSourcedid))
                        {
                            var outcome = await db.Outcomes.SingleOrDefaultAsync(o =>
                                o.ConsumerId == consumer.ConsumerId
                                && o.LisResultSourcedId == lisResultSourcedid);

                            if (outcome == null)
                            {
                                outcome = new Outcome
                                {
                                    ConsumerId = consumer.ConsumerId,
                                    LisResultSourcedId = lisResultSourcedid
                                };
                                db.Outcomes.Add(outcome);
                                await db.SaveChangesAsync(); // Assign OutcomeId;
                            }
                            outcome.ContextTitle = context.LtiRequest.ContextTitle;
                            outcome.ServiceUrl = lisOutcomeServiceUrl;
                            await db.SaveChangesAsync();

                            // Add the outcome ID as a claim
                            claims.Add(new Claim("OutcomeId",
                                outcome.OutcomeId.ToString(CultureInfo.InvariantCulture)));
                        }

                        // Sign in
                        await SecurityHandler.OnAuthenticated<ApplicationUserManager, ApplicationUser>(
                            context, claims);
                    },

                    // Generate a username using the LisPersonEmailPrimary from the LTI request
                    OnGenerateUserName = async context =>
                        await SecurityHandler.OnGenerateUserName(context)
                },
                ChallengeResultUrl = new PathString("/Manage/ToolConsumerLogins"),
                SignInAsAuthenticationType = DefaultAuthenticationTypes.ApplicationCookie
            });

        }
Esempio n. 12
0
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ProviderContext.Create);
            app.CreatePerOwinContext <LtiUserManager>(LtiUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);
            // The app also uses a RoleManager
            app.CreatePerOwinContext <ApplicationRoleManager>(ApplicationRoleManager.Create);

            app.UseLtiAuthentication(new LtiAuthenticationOptions
            {
                Provider = new LtiAuthenticationProvider
                {
                    // Look up the secret for the consumer
                    OnAuthenticate = async context =>
                    {
                        // Make sure the request is not being replayed
                        var timeout = TimeSpan.FromMinutes(5);
                        var oauthTimestampAbsolute = OAuthConstants.Epoch.AddSeconds(context.LtiRequest.Timestamp);
                        if (DateTime.UtcNow - oauthTimestampAbsolute > timeout)
                        {
                            throw new LtiException("Expired " + OAuthConstants.TimestampParameter);
                        }

                        var db       = context.OwinContext.Get <ProviderContext>();
                        var consumer = await db.Consumers.SingleOrDefaultAsync(c => c.Key == context.LtiRequest.ConsumerKey);
                        if (consumer == null)
                        {
                            throw new LtiException("Invalid " + OAuthConstants.ConsumerKeyParameter);
                        }

                        var signature = context.LtiRequest.GenerateSignature(consumer.Secret);
                        if (!signature.Equals(context.LtiRequest.Signature))
                        {
                            throw new LtiException("Invalid " + OAuthConstants.SignatureParameter);
                        }

                        // If we made it this far the request is valid
                    },

                    // Sign in using application authentication. This handler will create a new application
                    // user if no matching application user is found.
                    OnAuthenticated = async context =>
                    {
                        var db       = context.OwinContext.Get <ProviderContext>();
                        var consumer = await db.Consumers.SingleOrDefaultAsync(c => c.Key.Equals(context.LtiRequest.ConsumerKey));
                        if (consumer == null)
                        {
                            return;
                        }

                        // Record the request for logging purposes and as reference for outcomes
                        var providerRequest = new ProviderRequest
                        {
                            Received   = DateTime.UtcNow,
                            LtiRequest = JsonConvert.SerializeObject(context.LtiRequest, Formatting.None,
                                                                     new JsonSerializerSettings {
                                NullValueHandling = NullValueHandling.Ignore
                            })
                        };
                        db.ProviderRequests.Add(providerRequest);
                        db.SaveChanges();

                        // Add the requst ID as a claim
                        var claims = new List <Claim>
                        {
                            new Claim("ProviderRequestId",
                                      providerRequest.ProviderRequestId.ToString(CultureInfo.InvariantCulture))
                        };

                        // Outcomes can live a long time to give the teacher enough
                        // time to grade the assignment. So they are stored in a separate table.
                        var lisOutcomeServiceUrl = ((IOutcomesManagementRequest)context.LtiRequest).LisOutcomeServiceUrl;
                        var lisResultSourcedid   = ((IOutcomesManagementRequest)context.LtiRequest).LisResultSourcedId;
                        if (!string.IsNullOrWhiteSpace(lisOutcomeServiceUrl) &&
                            !string.IsNullOrWhiteSpace(lisResultSourcedid))
                        {
                            var outcome = await db.Outcomes.SingleOrDefaultAsync(o =>
                                                                                 o.ConsumerId == consumer.ConsumerId &&
                                                                                 o.LisResultSourcedId == lisResultSourcedid);

                            if (outcome == null)
                            {
                                outcome = new Outcome
                                {
                                    ConsumerId         = consumer.ConsumerId,
                                    LisResultSourcedId = lisResultSourcedid
                                };
                                db.Outcomes.Add(outcome);
                                await db.SaveChangesAsync(); // Assign OutcomeId;
                            }
                            outcome.ContextTitle = context.LtiRequest.ContextTitle;
                            outcome.ServiceUrl   = lisOutcomeServiceUrl;
                            await db.SaveChangesAsync();

                            // Add the outcome ID as a claim
                            claims.Add(new Claim("OutcomeId",
                                                 outcome.OutcomeId.ToString(CultureInfo.InvariantCulture)));
                        }

                        // Sign in
                        await SecurityHandler.OnAuthenticated <LtiUserManager, LtiUser>(
                            context, claims);
                    },

                    // Generate a username using the LisPersonEmailPrimary from the LTI request
                    OnGenerateUserName = async context =>
                                         await SecurityHandler.OnGenerateUserName(context)
                },
                //ChallengeResultUrl = new PathString("/Manage/ToolConsumerLogins"),
                SignInAsAuthenticationType = DefaultAuthenticationTypes.ApplicationCookie
            });
        }
Esempio n. 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, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ProviderContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);
            // The app also uses a RoleManager
            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
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                CookieName         = ".Provider.AspNet.Cookies",
                LoginPath          = new PathString("/Account/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

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


            app.UseLtiAuthentication(new LtiAuthenticationOptions
            {
                Provider = new LtiAuthenticationProvider
                {
                    // Look up the secret for the consumer
                    OnAuthenticate = async context =>
                    {
                        // Make sure the request is not being replayed
                        var timeout = TimeSpan.FromMinutes(5);
                        var oauthTimestampAbsolute = OAuthConstants.Epoch.AddSeconds(context.LtiRequest.Timestamp);
                        if (DateTime.UtcNow - oauthTimestampAbsolute > timeout)
                        {
                            throw new LtiException("Expired " + OAuthConstants.TimestampParameter);
                        }

                        var db       = context.OwinContext.Get <ProviderContext>();
                        var consumer = await db.Consumers.SingleOrDefaultAsync(c => c.Key == context.LtiRequest.ConsumerKey);
                        if (consumer == null)
                        {
                            throw new LtiException("Invalid " + OAuthConstants.ConsumerKeyParameter);
                        }

                        var signature = context.LtiRequest.GenerateSignature(consumer.Secret);
                        if (!signature.Equals(context.LtiRequest.Signature))
                        {
                            throw new LtiException("Invalid " + OAuthConstants.SignatureParameter);
                        }

                        // If we made it this far the request is valid
                    },

                    // Sign in using application authentication. This handler will create a new application
                    // user if no matching application user is found.
                    OnAuthenticated = async context =>
                    {
                        var db       = context.OwinContext.Get <ProviderContext>();
                        var consumer = await db.Consumers.SingleOrDefaultAsync(c => c.Key.Equals(context.LtiRequest.ConsumerKey));
                        if (consumer == null)
                        {
                            return;
                        }

                        // Record the request for logging purposes and as reference for outcomes
                        var providerRequest = new ProviderRequest
                        {
                            Received   = DateTime.UtcNow,
                            LtiRequest = JsonConvert.SerializeObject(context.LtiRequest, Formatting.None,
                                                                     new JsonSerializerSettings {
                                NullValueHandling = NullValueHandling.Ignore
                            })
                        };
                        db.ProviderRequests.Add(providerRequest);
                        db.SaveChanges();

                        // Add the requst ID as a claim
                        var claims = new List <Claim>
                        {
                            new Claim("ProviderRequestId",
                                      providerRequest.ProviderRequestId.ToString(CultureInfo.InvariantCulture))
                        };

                        // Outcomes can live a long time to give the teacher enough
                        // time to grade the assignment. So they are stored in a separate table.
                        var lisOutcomeServiceUrl = ((IOutcomesManagementRequest)context.LtiRequest).LisOutcomeServiceUrl;
                        var lisResultSourcedid   = ((IOutcomesManagementRequest)context.LtiRequest).LisResultSourcedId;
                        if (!string.IsNullOrWhiteSpace(lisOutcomeServiceUrl) &&
                            !string.IsNullOrWhiteSpace(lisResultSourcedid))
                        {
                            var outcome = await db.Outcomes.SingleOrDefaultAsync(o =>
                                                                                 o.ConsumerId == consumer.ConsumerId &&
                                                                                 o.LisResultSourcedId == lisResultSourcedid);

                            if (outcome == null)
                            {
                                outcome = new Outcome
                                {
                                    ConsumerId         = consumer.ConsumerId,
                                    LisResultSourcedId = lisResultSourcedid
                                };
                                db.Outcomes.Add(outcome);
                                await db.SaveChangesAsync(); // Assign OutcomeId;
                            }
                            outcome.ContextTitle = context.LtiRequest.ContextTitle;
                            outcome.ServiceUrl   = lisOutcomeServiceUrl;
                            await db.SaveChangesAsync();

                            // Add the outcome ID as a claim
                            claims.Add(new Claim("OutcomeId",
                                                 outcome.OutcomeId.ToString(CultureInfo.InvariantCulture)));
                        }

                        // Sign in
                        await SecurityHandler.OnAuthenticated <ApplicationUserManager, ApplicationUser>(
                            context, claims);
                    },

                    // Generate a username using the LisPersonEmailPrimary from the LTI request
                    OnGenerateUserName = async context =>
                                         await SecurityHandler.OnGenerateUserName(context)
                },
                ChallengeResultUrl         = new PathString("/Manage/ToolConsumerLogins"),
                SignInAsAuthenticationType = DefaultAuthenticationTypes.ApplicationCookie
            });
        }
Esempio n. 14
0
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ProviderContext.Create);
            app.CreatePerOwinContext<LtiUserManager>(LtiUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
            // The app also uses a RoleManager
            app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

            app.UseLtiAuthentication(new LtiAuthenticationOptions
            {
                Provider = new LtiAuthenticationProvider
                {
                    // Look up the secret for the consumer
                    OnAuthenticate = async context =>
                    {
                        // Make sure the request is not being replayed
                        var timeout = TimeSpan.FromMinutes(5);
                        var oauthTimestampAbsolute = OAuthConstants.Epoch.AddSeconds(context.LtiRequest.Timestamp);
                        if (DateTime.UtcNow - oauthTimestampAbsolute > timeout)
                        {
                            throw new LtiException("Expired " + OAuthConstants.TimestampParameter);
                        }

                        var db = context.OwinContext.Get<ProviderContext>();
                        var consumer = await db.Consumers.SingleOrDefaultAsync(c => c.Key == context.LtiRequest.ConsumerKey);
                        if (consumer == null)
                        {
                            throw new LtiException("Invalid " + OAuthConstants.ConsumerKeyParameter);
                        }

                        var signature = context.LtiRequest.GenerateSignature(consumer.Secret);
                        if (!signature.Equals(context.LtiRequest.Signature))
                        {
                            throw new LtiException("Invalid " + OAuthConstants.SignatureParameter);
                        }

                        // If we made it this far the request is valid
                    },

                    // Sign in using application authentication. This handler will create a new application
                    // user if no matching application user is found.
                    OnAuthenticated = async context =>
                    {
                        var db = context.OwinContext.Get<ProviderContext>();
                        var consumer = await db.Consumers.SingleOrDefaultAsync(c => c.Key.Equals(context.LtiRequest.ConsumerKey));
                        if (consumer == null) return;

                        // Record the request for logging purposes and as reference for outcomes
                        var providerRequest = new ProviderRequest
                        {
                            Received = DateTime.UtcNow,
                            LtiRequest = JsonConvert.SerializeObject(context.LtiRequest, Formatting.None,
                            new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore })
                        };
                        db.ProviderRequests.Add(providerRequest);
                        db.SaveChanges();

                        // Add the requst ID as a claim
                        var claims = new List<Claim>
                        {
                            new Claim("ProviderRequestId",
                                providerRequest.ProviderRequestId.ToString(CultureInfo.InvariantCulture))
                        };

                        // Outcomes can live a long time to give the teacher enough
                        // time to grade the assignment. So they are stored in a separate table.
                        var lisOutcomeServiceUrl = ((IOutcomesManagementRequest)context.LtiRequest).LisOutcomeServiceUrl;
                        var lisResultSourcedid = ((IOutcomesManagementRequest)context.LtiRequest).LisResultSourcedId;
                        if (!string.IsNullOrWhiteSpace(lisOutcomeServiceUrl)
                            && !string.IsNullOrWhiteSpace(lisResultSourcedid))
                        {
                            var outcome = await db.Outcomes.SingleOrDefaultAsync(o =>
                                o.ConsumerId == consumer.ConsumerId
                                && o.LisResultSourcedId == lisResultSourcedid);

                            if (outcome == null)
                            {
                                outcome = new Outcome
                                {
                                    ConsumerId = consumer.ConsumerId,
                                    LisResultSourcedId = lisResultSourcedid
                                };
                                db.Outcomes.Add(outcome);
                                await db.SaveChangesAsync(); // Assign OutcomeId;
                            }
                            outcome.ContextTitle = context.LtiRequest.ContextTitle;
                            outcome.ServiceUrl = lisOutcomeServiceUrl;
                            await db.SaveChangesAsync();

                            // Add the outcome ID as a claim
                            claims.Add(new Claim("OutcomeId",
                                outcome.OutcomeId.ToString(CultureInfo.InvariantCulture)));
                        }

                        // Sign in
                        await SecurityHandler.OnAuthenticated<LtiUserManager, LtiUser>(
                            context, claims);
                    },

                    // Generate a username using the LisPersonEmailPrimary from the LTI request
                    OnGenerateUserName = async context =>
                        await SecurityHandler.OnGenerateUserName(context)
                },
                //ChallengeResultUrl = new PathString("/Manage/ToolConsumerLogins"),
                SignInAsAuthenticationType = DefaultAuthenticationTypes.ApplicationCookie
            });
        }