1

I need to change LaginPath dynamically. I have a custom culture in my project. if the language is Engilish, LoginPath= "/Login" if the language is Turkish, LoginPath= "/Oturum-Ac"

how can I change LoginPath dynamically

Can you give me code example how to override/change CookieAuthenticationOptions in CustomCulture

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
using Microsoft.EntityFrameworkCore;
using ECommerce.Entity;
using ECommerce.Repository.Abstract;
using System;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ECommerce.WebUI.Infrastructure;
using System.IO;
using System.Text;
using ECommerce.WebUI.Areas.Admin.Infrastructure;
using System.Net;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Identity;

namespace ECommerce.WebUI.Infrastructure
{
    public class CustomCulture
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<CustomCulture> _logger;

        public CustomCulture(RequestDelegate next, ILogger<CustomCulture> logger)
        {
            _next = next;
            _logger = logger;

        }

        public async Task InvokeAsync(HttpContext context)
        {
            int languageId = context.Session.GetJSon<int>("LanguageId");
            var unitOfWork = (IUnitOfWork)context.RequestServices.GetService(typeof(IUnitOfWork));
            var test = (CookieAuthenticationOptions)context.RequestServices.GetService(typeof(CookieAuthenticationOptions));
            //test.LoginPath = "/NewLoginPath";
            var requestPath = context.Request.Path.Value;
            if (!string.IsNullOrEmpty(requestPath) && requestPath[0] == '/')
            {
                requestPath = requestPath.Substring(1);
            }
            var segments = requestPath.Split('/');

            string firstSegment = segments[0] ?? "";
            var set = false;
            Language Language = null;

            //check cookie 
            var locOptions = (IOptions<RequestLocalizationOptions>)context.RequestServices.GetService(typeof(IOptions<RequestLocalizationOptions>));
            if (string.IsNullOrEmpty(locOptions.Value.DefaultRequestCulture.Culture.Name))
            {
                languageId = 0;
            }

            if (firstSegment != "" && firstSegment.ToLower() != "admin" && firstSegment != "GetJsonList")
            {
                var getReturnUrlSegments = WebUtility.UrlDecode(WebUtility.UrlDecode(context.Request.QueryString.ToUriComponent().ToLower())).Split('/');
                var pageUrl = WebUtility.UrlDecode(getReturnUrlSegments[getReturnUrlSegments.Length - 1]);//last part of returnUrl 

                _logger.LogTrace($"CustomCulture - set FromUrl : {pageUrl}");

                Language = unitOfWork.Pages.GetAll().Include(i => i.Language)
                                                    .Where(i => i.PageRoot.RootName.ToLower() == segments[0].ToLower() ||
                                                                i.Url.ToLower() == segments[0].ToLower() ||
                                                                i.Url.ToLower() == pageUrl).FirstOrDefault().Language;
                if (Language != null)
                {
                    if (Language.LanguageId != languageId)
                    {
                        languageId = Language.LanguageId;
                        set = true; //set cookie and sesion
                    }
                }

                #region SET GetLogin GetLogout GetAccessDenied

                if (segments[0] == "GetLogin" || segments[0] == "GetLogout" || segments[0] == "GetAccessDenied")
                {
                    var returnUrlSegments = WebUtility.UrlDecode(WebUtility.UrlDecode(context.Request.QueryString.ToUriComponent().ToLower()))
                                                                .Split("returnurl=");
                    //find how many returnUrl with returnUrlSegments.Length - 1
                    var setReturnUrl = returnUrlSegments[returnUrlSegments.Length - 1];
                    returnUrlSegments = setReturnUrl.Substring(1).Split('/');
                    ///////////
                    var page = unitOfWork.Pages.GetAll().Include(i => i.PageRoot).ThenInclude(i => i.Language)
                                                    .Where(i => i.IsApproved && i.Language.IsApproved &&
                                                                i.LanguageId == languageId &&
                                                                i.PageRoot.ControllerName == "Account" &&
                                                                i.PageRoot.ActionName == segments[0].Replace("Get", "")).FirstOrDefault();

                    var redirectUrl = "/" + page.PageRoot.RootName + "/" + page.Url + "?ReturnUrl=" + setReturnUrl;

                    context.Response.Redirect(redirectUrl);
                    return;
                }

                #endregion
            }

            #region SET DEFAULT CULTURE

            if (languageId == 0)
            {
                var cultureFromBrowser = Thread.CurrentThread.CurrentCulture.ToString();
                if (Language == null)
                {
                    Language = unitOfWork.Languages.GetAll().Where(i => i.Culture == cultureFromBrowser &&
                                                                        i.IsApproved)
                                                            .FirstOrDefault();
                    if (Language == null)
                    {
                        Language = unitOfWork.Languages.GetAll()
                                            .Where(i => i.ShortLang == cultureFromBrowser.Substring(0, 2) &&
                                                        i.IsApproved)
                                            .FirstOrDefault();
                        if (Language == null)
                        {
                            Language = unitOfWork.Languages.GetAll()
                                           .Where(i => i.IsApproved).OrderBy(i => i.SortOrder)
                                           .FirstOrDefault();
                        }
                    }
                    set = true; //set cookie and sesion
                }
            }

            #endregion

            #region SET COOKIE AND SESSION

            if (set)
            {
                _logger.LogTrace($"CustomCulture - set CULTURE/SESSION/CULTURE COOKIE/CURRENCY COOKIE");

                //SET CULTURE
                var culture = new CultureInfo(Language.Culture);
                CultureInfo.CurrentCulture = culture;
                CultureInfo.CurrentUICulture = culture;

                //SET SESSION
                context.Session.SetJson("LanguageId", Language.LanguageId);
                context.Session.SetJson("Culture", Language.Culture);
                context.Session.SetJson("SettingLanguageId", Language.LanguageId);
                //SET CULTURE COOKIE
                context.Response.Cookies.Append(CookieRequestCultureProvider.DefaultCookieName,
                            CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(Language.Culture)),
                            new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) });

                //SET CURRENCY COOKİE
                context.Response.Cookies.Append("CurrencyId", Language.CurrencyId.ToString(),
                                                    new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) });
            }

            #endregion

            _logger.LogInformation($"CustomCulture -  languageId : {languageId}");

            await this._next(context);

        }
    }
}
1
  • Could you use Url Rewriter and Url Redirect?learn.microsoft.com/en-us/aspnet/core/fundamentals/… When you click login button( /identity/Login), it will redirect to Login action ,check current culture and then rewrite the url on browser Commented Aug 23, 2019 at 3:18

2 Answers 2

7

A workaround is that you could implement a  custom CookieAuthenticationEvents using your above code and change the RedirectUri:

public class MyCookieAuthenticationEvents : CookieAuthenticationEvents
{
    public override Task RedirectToLogin(RedirectContext<CookieAuthenticationOptions> redirectContext)
    {
        //get HttpContext
        var context = redirectContext.HttpContext;
        //your above logic omitted
        //...
        redirectContext.RedirectUri = "Your new url";
        return base.RedirectToLogin(redirectContext);
    }
}

Register in startup.cs

services.ConfigureApplicationCookie(options =>
        {
           //...
            options.LoginPath = "/GetLogin";
            options.LogoutPath = "/GetLogout";
            options.AccessDeniedPath = "/GetAccessDenied";
            options.SlidingExpiration = true;
            options.EventsType = typeof(MyCookieAuthenticationEvents);
        });
services.AddScoped<MyCookieAuthenticationEvents>();
Sign up to request clarification or add additional context in comments.

Comments

0

thank you very much Xing Zou.

can you see any problem in my code. It is working because of you.

I have a question can I override services.Configure

    services.Configure<IdentityOptions>(options =>
    {
        // Password settings.
        options.Password.RequireDigit = true;
        options.Password.RequireLowercase = true;
        options.Password.RequireNonAlphanumeric = true;
        options.Password.RequireUppercase = true;
        options.Password.RequiredLength = 6;
        options.Password.RequiredUniqueChars = 1;

        // Lockout settings.
        options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);

        options.Lockout.MaxFailedAccessAttempts = 5;
        options.Lockout.AllowedForNewUsers = true;

        // User settings.
        options.User.AllowedUserNameCharacters =
        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
        options.User.RequireUniqueEmail = true;
    });

this is working

public class CustomCookieAuthenticationEvents  : CookieAuthenticationEvents
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ILogger<CustomCookieAuthenticationEvents> _logger;

        public CustomCookieAuthenticationEvents(IUnitOfWork unitOfWork, ILogger<CustomCookieAuthenticationEvents> logger)
        {
            _unitOfWork = unitOfWork;
            _logger = logger; // _logger.LogInformation($"{}");
        }

        public override Task RedirectToLogin(RedirectContext<CookieAuthenticationOptions> redirectContext)
        {
            //get HttpContext
            var context = redirectContext.HttpContext;
            var returnUrl = context.Request.PathAndQuery();
            var culture = Thread.CurrentThread.CurrentCulture.ToString();
            //Login
            var page = _unitOfWork.Pages.GetAll().Include(i => i.PageRoot).ThenInclude(i => i.Language)
                                                .Where(i => i.IsApproved && i.Language.IsApproved &&
                                                            i.Language.Culture == culture &&
                                                            i.PageRoot.ControllerName == "Account" &&
                                                            i.PageRoot.ActionName == "Login").FirstOrDefault();
            var redirectToLoginUrl = page == null ? "/Login" :
                                        page.PageRoot == null || string.IsNullOrEmpty(page.PageRoot.RootName) ? "" :
                                            "/" + page.PageRoot.RootName + "/" + page.Url 
                                                + "?ReturnUrl=" + returnUrl;
            redirectContext.RedirectUri = redirectToLoginUrl;
            _logger.LogTrace($"CustomCookieAuthenticationEvents - Login Path {redirectToLoginUrl}");
            return base.RedirectToLogin(redirectContext);
        }

        public override Task RedirectToLogout(RedirectContext<CookieAuthenticationOptions> redirectContext)
        {
            //get HttpContext
            var context = redirectContext.HttpContext;
            var returnUrl = context.Request.PathAndQuery();
            var culture = Thread.CurrentThread.CurrentCulture.ToString();

            //Logout
            var page = _unitOfWork.Pages.GetAll().Include(i => i.PageRoot).ThenInclude(i => i.Language)
                                                .Where(i => i.IsApproved && i.Language.IsApproved &&
                                                            i.Language.Culture == culture &&
                                                            i.PageRoot.ControllerName == "Account" &&
                                                            i.PageRoot.ActionName == "Logout").FirstOrDefault();
            var redirectToLogoutUrl = page == null ? "/Logout" :
                                        page.PageRoot == null || string.IsNullOrEmpty(page.PageRoot.RootName) ? "" :
                                            "/" + page.PageRoot.RootName + "/" + page.Url +
                                            "?ReturnUrl=" + returnUrl;
            redirectContext.RedirectUri = redirectToLogoutUrl;
            _logger.LogTrace($"CustomCookieAuthenticationEvents - Logout Path {redirectToLogoutUrl}");
            return base.RedirectToLogout(redirectContext);
        }

        public override Task RedirectToAccessDenied(RedirectContext<CookieAuthenticationOptions> redirectContext)
        {
            //get HttpContext
            var context = redirectContext.HttpContext;
            var returnUrl = context.Request.PathAndQuery();
            var culture = Thread.CurrentThread.CurrentCulture.ToString();
            //AccessDenied
            var page = _unitOfWork.Pages.GetAll().Include(i => i.PageRoot).ThenInclude(i => i.Language)
                                                .Where(i => i.IsApproved && i.Language.IsApproved &&
                                                            i.Language.Culture == culture &&
                                                            i.PageRoot.ControllerName == "Account" &&
                                                            i.PageRoot.ActionName == "AccessDenied").FirstOrDefault();
            var redirectToAccessDeniedUrl = page == null ? "/AccessDenied" :
                                        page.PageRoot == null || string.IsNullOrEmpty(page.PageRoot.RootName) ? "" :
                                            "/" + page.PageRoot.RootName + "/" + page.Url 
                                                + "?ReturnUrl=" + returnUrl;
            redirectContext.RedirectUri = redirectToAccessDeniedUrl;
            _logger.LogTrace($"CustomCookieAuthenticationEvents - AccessDenied Path {redirectToAccessDeniedUrl}");

            return base.RedirectToAccessDenied(redirectContext);
        }

    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.