/// <summary> /// Configures the application authentication. /// </summary> public void Configuration(IAppBuilder app) { // Register Kentico Membership identity implementation app.CreatePerOwinContext(() => KenticoUserManager.Initialize(app, new KenticoUserManager(new KenticoUserStore(SiteContext.CurrentSiteName)))); app.CreatePerOwinContext <KenticoSignInManager>(KenticoSignInManager.Create); // Configure the sign in cookie UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/"), Provider = new CookieAuthenticationProvider { OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <KenticoUserManager, User, int>( // Sets the interval after which the validity of the user's security stamp is checked validateInterval: TimeSpan.FromMinutes(1), regenerateIdentityCallback: (manager, user) => manager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie), getUserIdCallback: ((claimsIdentity) => int.Parse(claimsIdentity.GetUserId()))), // Redirect to logon page with return url OnApplyRedirect = context => context.Response.Redirect(urlHelper.Action("Login", "Account") + new Uri(context.RedirectUri).Query) }, ExpireTimeSpan = TimeSpan.FromDays(14), SlidingExpiration = true, CookieName = AUTHENTICATION_COOKIE_NAME }); // Register the authentication cookie in the Kentico application and set its cookie level. // This will ensure that the authentication cookie will not be removed when a user revokes the tracking consent. CookieHelper.RegisterCookie(AUTHENTICATION_COOKIE_NAME, CookieLevel.Essential); }
public void Configuration(IAppBuilder app) { // Registers the Kentico.Membership identity implementation app.CreatePerOwinContext(() => KenticoUserManager.Initialize(app, new KenticoUserManager(new KenticoUserStore(SiteContext.CurrentSiteName)))); app.CreatePerOwinContext <KenticoSignInManager>(KenticoSignInManager.Create); // Configures the authentication cookie UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, // Fill in the name of your sign-in action and controller LoginPath = new PathString(urlHelper.Action("SignIn", "Account")), Provider = new CookieAuthenticationProvider { // Sets the return URL for the sign-in page redirect (fill in the name of your sign-in action and controller) OnApplyRedirect = context => context.Response.Redirect(urlHelper.Action("SignIn", "Account") + new Uri(context.RedirectUri).Query) } }); // Registers the authentication cookie with the 'Essential' cookie level // Ensures that the cookie is preserved when changing a visitor's allowed cookie level below 'Visitor' CookieHelper.RegisterCookie(OWIN_COOKIE_PREFIX + DefaultAuthenticationTypes.ApplicationCookie, CookieLevel.Essential); }
public async Task <ActionResult> ManageRoles(string action) { switch (action) { case "add": try { //DocSection:AddRole // Attempts to assign the current user to the "KenticoRole" and "CMSBasicUsers" roles IdentityResult addResult = await KenticoUserManager.AddToRolesAsync(CurrentUser.Id, "KenticoRole", "CMSBasicUsers"); //EndDocSection:AddRole } catch (Exception exception) { // Adds error messages onto the role management page (for example if the roles do not exist in the system) ModelState.AddModelError("", string.Format("Exception: {0}", exception.Message)); } return(View(CurrentUser)); case "remove": //DocSection:RemoveRole // Attempts to remove the "KenticoRole" and "CMSBasicUsers" roles from the current user IdentityResult removeResult = await KenticoUserManager.RemoveFromRolesAsync(CurrentUser.Id, "KenticoRole", "CMSBasicUsers"); //EndDocSection:RemoveRole return(View(CurrentUser)); default: return(View(CurrentUser)); } }
public async Task <ActionResult> SignIn(SignInViewModel model, string returnUrl) { // Validates the received user credentials based on the view model if (!ModelState.IsValid) { // Displays the sign-in form if the user credentials are invalid return(View()); } // Attempts to authenticate the user against the Xperience database SignInStatus signInResult = SignInStatus.Failure; try { signInResult = await KenticoSignInManager.PasswordSignInAsync(model.UserName, model.Password, model.SignInIsPersistent, false); } catch (Exception ex) { // Logs an error into the Xperience event log if the authentication fails eventLogService.LogException("MvcApplication", "SignIn", ex); } // If the authentication was successful, redirects to the return URL when possible or to a different default action if (signInResult == SignInStatus.Success) { string decodedReturnUrl = Server.UrlDecode(returnUrl); if (!string.IsNullOrEmpty(decodedReturnUrl) && Url.IsLocalUrl(decodedReturnUrl)) { return(Redirect(decodedReturnUrl)); } return(RedirectToAction("Index", "Home")); } // If the 'Registration requires administrator's approval' setting is enabled and the user account // is pending activation, displays an appropriate message if (signInResult == SignInStatus.LockedOut) { // If the 'Registration requires administrator's approval' setting is enabled and the user account // is pending activation, displays an appropriate message User user = await KenticoUserManager.FindByNameAsync(model.UserName); if (user.WaitingForApproval) { ModelState.AddModelError(String.Empty, "You account is pending administrator approval."); } return(View()); } // If the authentication was not successful, displays the sign-in form with an "Authentication failed" message ModelState.AddModelError(String.Empty, "Authentication failed"); return(View()); }
private async void DummyRoleCheckMethod() { KenticoUserManager UserManager = HttpContext.GetOwinContext().Get <KenticoUserManager>(); User CurrentUser = UserManager.FindByName(User.Identity.Name); //DocSection:CheckRole // Checks whether the current user is assigned to the "KenticoRole" role if (await UserManager.IsInRoleAsync(CurrentUser.Id, "KenticoRole")) { // ... } //EndDocSection:CheckRole }
public async Task <IdentityResult> RegisterUser(RegisterModel userRegister) { KenticoUserManager <DubaiCultureUser> t = new KenticoUserManager <DubaiCultureUser>(new KenticoUserStore <DubaiCultureUser>(AppConfig.SiteName)); DubaiCultureUser user = new DubaiCultureUser { UserName = userRegister.UserName, FirstName = userRegister.FirstName, LastName = userRegister.LastName, Email = userRegister.UserName, Enabled = true }; IdentityResult result = await _userManager.CreateAsync(user, userRegister.Password); return(result); }
/// <summary> /// Creates users in Xperience based on external login data. /// </summary> private async Task <IdentityResult> CreateExternalUser(ExternalLoginInfo loginInfo) { // Prepares a new user entity based on the external login data Kentico.Membership.User user = new User { UserName = ValidationHelper.GetSafeUserName(loginInfo.DefaultUserName ?? loginInfo.Email, SiteContext.CurrentSiteName), Email = loginInfo.Email, Enabled = true, // The user is enabled by default IsExternal = true // IsExternal must always be true for users created via external authentication // Set any other required user properties using the data available in loginInfo }; // Attempts to create the user in the Xperience database IdentityResult result = await KenticoUserManager.CreateAsync(user); if (result.Succeeded) { // If the user was created successfully, creates a mapping between the user and the given authentication provider result = await KenticoUserManager.AddLoginAsync(user.Id, loginInfo.Login); } return(result); }
public AuthRepository() { _userManager = new KenticoUserManager <DubaiCultureUser>(new KenticoUserStore <DubaiCultureUser>(AppConfig.SiteName)); // _signInManager = new KenticoSignInManager<KenticoUser>(_userManager, AuthenticationManager); }
public void Configuration(IAppBuilder app) { // Registers the Kentico.Membership identity implementation app.CreatePerOwinContext(() => KenticoUserManager.Initialize(app, new KenticoUserManager(new KenticoUserStore(SiteContext.CurrentSiteName)))); app.CreatePerOwinContext <KenticoSignInManager>(KenticoSignInManager.Create); // Configures the authentication cookie UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, // Fill in the name of your sign-in action and controller LoginPath = new PathString(urlHelper.Action("SignIn", "Account")), Provider = new CookieAuthenticationProvider { // Sets the return URL for the sign-in page redirect (fill in the name of your sign-in action and controller) OnApplyRedirect = context => context.Response.Redirect(urlHelper.Action("SignIn", "Account") + new Uri(context.RedirectUri).Query) } }); // Registers the authentication cookie with the 'Essential' cookie level // Ensures that the cookie is preserved when changing a visitor's allowed cookie level below 'Visitor' CookieHelper.RegisterCookie(OWIN_COOKIE_PREFIX + DefaultAuthenticationTypes.ApplicationCookie, CookieLevel.Essential); // Uses a cookie to temporarily store information about users signing in via external authentication services app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Registers a WS-Federation authentication service app.UseWsFederationAuthentication( new WsFederationAuthenticationOptions { // Set any properties required by your authentication service MetadataAddress = "placeholder", // Fill in the address of your service's WS-Federation metadata Wtrealm = "", // When using external services, Passive authentication mode may help avoid redirect loops for 401 responses AuthenticationMode = AuthenticationMode.Passive }); // Registers an OpenID Connect authentication service app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { // Set any properties required by your authentication service ClientId = "placeholder", ClientSecret = "placeholder", Authority = "https://placeholder", AuthenticationMode = AuthenticationMode.Passive }); // Registers the Facebook authentication service app.UseFacebookAuthentication( new FacebookAuthenticationOptions { // Fill in the application ID and secret of your Facebook authentication application AppId = "placeholder", AppSecret = "placeholder" }); // Registers the Google authentication service app.UseGoogleAuthentication( new GoogleOAuth2AuthenticationOptions { // Fill in the client ID and secret of your Google authentication application ClientId = "placeholder", ClientSecret = "placeholder" }); }