Open Closed

LoginModel and LoggedOutModel is giving error while Migrating from IdentityServer to OpenIddict #7182


User avatar
0
Priyanka created

I'm trying to migrate IdentityServer to OpenIddict, I have followed these steps -https://docs.abp.io/en/abp/latest/Migration-Guides/OpenIddict-Step-by-Step but in my application I'm using LoginCustomModel which is inheriting LoginModel, but now after migration LoginModel is giving below error I'm using LoginCustomModel to overide OnGetExternalLoginCallbackAsync method. I'm getting same issue in CustomLogout as well where I'm inheriting LoggedOutModel to override OnGetAsync. Please help, how can I migrate LoginCustomModel and CustomLogout.

ABP Framework version: v8.1.1

UI Type:React

Database System: EF Core (SQL Server)

Tiered (for MVC) or Auth Server Separated (for Angular): yes

Exception message and full stack trace:NA

Steps to reproduce the issue: Migrate from IdentityServer to OpenIddict


47 Answer(s)
  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    The base class of LoginModel should be Volo.Abp.Account.Web.Pages.Account.OpenIddictSupportedLoginModel and the LoggedOutModel namespace is Volo.Abp.Account.Public.Web.Pages.Account LoggedOutModel

  • User Avatar
    0
    Priyanka created

    olo.Abp.Account.Web.Pages.Account.OpenIddictSupportedLoginModel

    This is also giving the error

    Let me know If I need to add some reference or exact name of class. I'm not getting anything in suggestion.

    Thank you.

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    These classes are in the Volo.Abp.Account.Pro.Public.Web.OpenIddict package.

    btw, can you share your csproj file of backed?

  • User Avatar
    0
    Priyanka created

    Volo.Abp.Account.Pro.Public.Web.OpenIddict No Package found for this

    Please find csproj file below

    <Project Sdk="Microsoft.NET.Sdk.Web">
    
    	<Import Project="..\..\common.props" />
    
    	<PropertyGroup>
    		<TargetFramework>net8.0</TargetFramework>
    		<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
    		<RootNamespace>eFC.Web</RootNamespace>
    		<AssetTargetFallback>$(AssetTargetFallback);portable-net45+win8+wp8+wpa81;</AssetTargetFallback>
    		<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
    		<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
    		<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
    		<PreserveCompilationContext>true</PreserveCompilationContext>
    		<MvcRazorExcludeRefAssembliesFromPublish>false</MvcRazorExcludeRefAssembliesFromPublish>
    		<PreserveCompilationReferences>true</PreserveCompilationReferences>
    		<UserSecretsId>48d09d73-95fd-4623-9199-be2c7853284a</UserSecretsId>
    		<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
    		<DockerfileContext>..\..</DockerfileContext>
    		<OutputType>Exe</OutputType>
    	</PropertyGroup>
    
    	<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    		<LangVersion>9.0</LangVersion>
    	</PropertyGroup>
    	<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    		<LangVersion>9.0</LangVersion>
    	</PropertyGroup>
    	<ItemGroup>
    		<Compile Remove="Logs\**" /> 
    		<Content Remove="Logs\**" /> 
    		<EmbeddedResource Remove="Logs\**" /> 
    		<None Remove="Logs\**" /> 
    		<None Remove="Controller\" />
    		<None Remove="Pages\Account\" />
    		<None Remove="Pages\ADFS\" />
    		<None Remove="System.DirectoryServices" />
    		<None Remove="System.DirectoryServices.AccountManagement" />
    		<None Remove="Microsoft.AspNetCore.DataProtection.EntityFrameworkCore" />
    		<None Remove="TextTemplate\ETBSBodyTemplate.tpl" />
    		<None Remove="TextTemplate\ETBSColumnTemplate.tpl" />
    		<None Remove="TextTemplate\ETBSHeaderTemplate.tpl" />
    		<None Remove="TextTemplate\ETBSPreviewBodyTemplate.tpl" />
    		<None Remove="TextTemplate\ETBSTotalEstimationTemplate.tpl" />
    		<None Remove="TextTemplate\FCTypeContactNoEmail.tpl" />
    		<None Remove="TextTemplate\FooterTemplate.tpl" />
    		<None Remove="TextTemplate\UserTeamEmail.tpl" />
    		<None Remove="TextTemplate\VisitCancellationEmail.tpl" />
    	</ItemGroup>
    
    	<ItemGroup>
    		<Content Include="Pages\**\*.js">
    			<CopyToOutputDirectory>Always</CopyToOutputDirectory>
    		</Content>
    		<Content Include="Pages\**\*.css">
    			<CopyToOutputDirectory>Always</CopyToOutputDirectory>
    		</Content>
    	</ItemGroup>
    
    	<ItemGroup>
    		<Compile Remove="eFCAbpClaimsPrincipalContributor.cs" />
    		<Compile Remove="eFCAbpClaimsService.cs" />
    		<Compile Remove="Pages\UploadedFiles\EditModal.cshtml.cs" />
    	</ItemGroup>
    
    	<ItemGroup>
    		<Content Remove="Pages\UploadedFiles\EditModal.cshtml" />
    	</ItemGroup>
    
    	<ItemGroup>
    		<PackageReference Include="AspNetCore.HealthChecks.UI" Version="8.0.1" />
    		<PackageReference Include="AspNetCore.HealthChecks.UI.Client" Version="8.0.1" />
    		<PackageReference Include="AspNetCore.HealthChecks.UI.InMemory.Storage" Version="8.0.1" />
    		<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="8.0.4" />
    		<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="8.0.0" />
    		<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.20.1" />
    		<PackageReference Include="Serilog.AspNetCore" Version="8.0.1" />
    		<PackageReference Include="Serilog.Sinks.Async" Version="1.5.0" />
    		<PackageReference Include="Microsoft.AspNetCore.Authentication.Google" Version="8.0.4" />
    		<PackageReference Include="Microsoft.AspNetCore.Authentication.MicrosoftAccount" Version="8.0.4" />
    		<PackageReference Include="Microsoft.AspNetCore.Authentication.Twitter" Version="8.0.4" />
    		<PackageReference Include="System.DirectoryServices.AccountManagement" Version="8.0.0" />
    		<PackageReference Include="Microsoft.AspNetCore.DataProtection.EntityFrameworkCore" Version="8.0.4" />
    	</ItemGroup>
    
    	<ItemGroup>
    		<ProjectReference Include="..\eFC.Application\eFC.Application.csproj" />
    		<ProjectReference Include="..\eFC.HttpApi\eFC.HttpApi.csproj" />
    		<ProjectReference Include="..\eFC.EntityFrameworkCore\eFC.EntityFrameworkCore.csproj" />
    		<PackageReference Include="Volo.Abp.Autofac" Version="8.1.1" />
    		<PackageReference Include="Volo.Abp.AspNetCore.Serilog" Version="8.1.1" />
    		<PackageReference Include="Volo.Abp.AspNetCore.Authentication.JwtBearer" Version="8.1.1" />
    		<PackageReference Include="Volo.Abp.Swashbuckle" Version="8.1.1" />
    		<PackageReference Include="Volo.Abp.FeatureManagement.Web" Version="8.1.1" />
    		<PackageReference Include="Volo.Abp.Account.Pro.Admin.Web" Version="8.1.1" />
    		<PackageReference Include="Volo.Abp.AuditLogging.Web" Version="8.1.1" />
    		<PackageReference Include="Volo.Abp.Identity.Pro.Web" Version="8.1.1" />
    		<PackageReference Include="Volo.Abp.LeptonTheme.Management.Web" Version="8.1.1" />
    		<PackageReference Include="Volo.Abp.IdentityServer.Web" Version="8.1.1" />
    		<PackageReference Include="Volo.Abp.LanguageManagement.Web" Version="8.1.1" />
    		<PackageReference Include="Volo.Saas.Host.Web" Version="8.1.1" />
    		<PackageReference Include="Volo.Abp.AspNetCore.Mvc.UI.Theme.Lepton" Version="8.1.1" />
    		<PackageReference Include="Volo.Abp.TextTemplateManagement.Web" Version="8.1.1" />
    	</ItemGroup>
    
    	
    </Project>
    
  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    Can you also share the screenshot of the project structure? Do you have AuthServer project?

  • User Avatar
    0
    Priyanka created

    hi

    Can you also share the screenshot of the project structure? Do you have AuthServer project?

    This is the project structure, I don't have AuthServer.

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    There is no account module in your Web project.

    Please add <PackageReference Include="Volo.Abp.Account.Pro.Public.Web.OpenIddict" Version="8.1.1" /> to it and try again.

    You can create a new template project to compare the csproj file.

  • User Avatar
    0
    Priyanka created

    There is no account module in your Web project.

    Please add <PackageReference Include="Volo.Abp.Account.Pro.Public.Web.OpenIddict" Version="8.1.1" /> to it and try again.

    You can create a new template project to compare the csproj file.

    After adding above package reference, I'm able to get the class, but in my existing function this is parameter
    and I return this

    now in OpenIddictSupportedLoginModel, this is the parameter should I use this to return

    Also, what is the replacement of these class highlighted in red

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    You should remove all Identity Server-related code.

    You can create a new template project to compare the code.

  • User Avatar
    0
    Priyanka created

    hi

    You should remove all Identity Server-related code.

    You can create a new template project to compare the code.

    yes, to remove identity server related code, I want to know, what would be the replacement of these classes: AbpIdentityWebModule AbpAccountPublicWebIdentityServerModule AbpIdentityServerWebModule IdentityMenuNames AbpIdentityServerMenuNames

    It is not present in this link as well -https://docs.abp.io/en/abp/latest/Migration-Guides/OpenIddict-Step-by-Step

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer
    AbpIdentityWebModule // Remain
    AbpAccountPublicWebIdentityServerModule //Replace with AbpAccountPublicWebOpenIddictModule
    AbpIdentityServerWebModule  //Replace with AbpOpenIddictProWebModule
    IdentityMenuNames// Remain
    AbpIdentityServerMenuNames// Replace with OpenIddictProMenus
    

    I recommend you to create a new project and check its code.

  • User Avatar
    0
    Priyanka created

    AbpOpenIddictProWebModule

    Can you please help me with reference for AbpOpenIddictProWebModule and OpenIddictProMenus ?

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    AbpOpenIddictProWebModule and OpenIddictProMenus(Volo.Abp.OpenIddict.Pro.Web.Menus) are exist onVolo.Abp.OpenIddict.Pro.Web package.

    I recommend you to create a new project and check its code.

  • User Avatar
    0
    Priyanka created

    recommend you to create a new project and check its code.

    Hi, May I know why you recommend creating a new project and check its code? also, what do you mean by creating a new project? New project for OpenIddict?

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    Exactly. The new template project uses OpenIddict as an OAuth2 server. So I recommend you to create it.

  • User Avatar
    0
    Priyanka created

    hi

    Exactly. The new template project uses OpenIddict as an OAuth2 server. So I recommend you to create it.

    sure, can you also help we with the replacement of AbpIdentityServerApplicationContractsModule , AbpIdentityServerHttpApiModule and AbpIdentityServerHttpApiClientModule

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    AbpIdentityServerApplicationContractsModule: AbpOpenIddictProApplicationContractsModule - Volo.Abp.OpenIddict.Pro.Application.Contracts

    AbpIdentityServerHttpApiModule : AbpOpenIddictProHttpApiModule - Volo.Abp.OpenIddict.Pro.HttpApi

    AbpIdentityServerHttpApiClientModule: AbpOpenIddictProHttpApiClientModule - Volo.Abp.OpenIddict.Pro.HttpApi.Client

  • User Avatar
    0
    Priyanka created

    hi

    AbpIdentityServerApplicationContractsModule: AbpOpenIddictProApplicationContractsModule - Volo.Abp.OpenIddict.Pro.Application.Contracts

    AbpIdentityServerHttpApiModule : AbpOpenIddictProHttpApiModule - Volo.Abp.OpenIddict.Pro.HttpApi

    AbpIdentityServerHttpApiClientModule: AbpOpenIddictProHttpApiClientModule - Volo.Abp.OpenIddict.Pro.HttpApi.Client

    Hi, I'm able to migrate with no compile time error but I'm getting below error (run time)

    Could you please help me if something is missed?

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    Please share the code of your web module.

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    And this is the commercial document for migration to openiddict

    https://docs.abp.io/en/commercial/latest/migration-guides/openIddict-step-by-step

  • User Avatar
    0
    Priyanka created

    And this is the commercial document for migration to openiddict

    https://docs.abp.io/en/commercial/latest/migration-guides/openIddict-step-by-step

    Hi, Thank you for the new link, I was using https://docs.abp.io/en/abp/latest/Migration-Guides/OpenIddict-Step-by-Step but now I have verified my code using https://docs.abp.io/en/commercial/latest/migration-guides/openIddict-step-by-step. Everything mentioned in the link is updated, I'm still getting the error, I'm sharing my WebModule.cs Code for reference

    namespace myApp.Web
    {
        [DependsOn(
            typeof(myAppHttpApiModule),
            typeof(myAppApplicationModule),
            typeof(myAppEntityFrameworkCoreModule),
            typeof(AbpAutofacModule),
            typeof(AbpIdentityWebModule),
            typeof(AbpAccountPublicWebOpenIddictModule),
            typeof(AbpAuditLoggingWebModule),
            typeof(LeptonThemeManagementWebModule),
            typeof(SaasHostWebModule),
            typeof(AbpAccountAdminWebModule),
            typeof(AbpOpenIddictProWebModule),
            typeof(LanguageManagementWebModule),
            typeof(AbpAspNetCoreMvcUiLeptonThemeModule),
            typeof(TextTemplateManagementWebModule),
            typeof(AbpSwashbuckleModule),
            typeof(AbpAspNetCoreSerilogModule)
            )]
        public class myAppWebModule : AbpModule
        {
            public override void PreConfigureServices(ServiceConfigurationContext context)
            {
                context.Services.PreConfigure<AbpMvcDataAnnotationsLocalizationOptions>(options =>
                {
                    options.AddAssemblyResource(
                        typeof(myAppResource),
                        typeof(myAppDomainModule).Assembly,
                        typeof(myAppDomainSharedModule).Assembly,
                        typeof(myAppApplicationModule).Assembly,
                        typeof(myAppApplicationContractsModule).Assembly,
                        typeof(myAppWebModule).Assembly
                    );
                });
                /* PreConfigure<IdentityBuilder>(identityBuilder =>
                   {
                       identityBuilder.AddSignInManager<CustomSignInManager>();
                   });*/
            }
    
            public override void ConfigureServices(ServiceConfigurationContext context)
            {
                var hostingEnvironment = context.Services.GetHostingEnvironment();
                var configuration = context.Services.GetConfiguration();
    
                Configure<AbpAntiForgeryOptions>(options =>
                {
                    options.AutoValidate = false;
                });
                context.Services.Configure<AbpExceptionHttpStatusCodeOptions>(options =>
                {
                    options.Map("USER_FE", HttpStatusCode.BadRequest);
                });
                context.Services.Configure<IdentityOptions>(options =>
                {
                    options.User.AllowedUserNameCharacters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";
                });
    
                Configure<AbpBackgroundJobOptions>(options =>
                {
                    options.IsJobExecutionEnabled = configuration.GetSection("BackgroundJob").GetValue<bool>("Enabled");
                });
    
                // using Microsoft.AspNetCore.DataProtection;
                context.Services.AddDataProtection()
                .PersistKeysToDbContext<myAppDbContext>();
                ConfigureBundles();
                ConfigureUrls(configuration);
                ConfigurePages(configuration);
                ConfigureAuthentication(context, configuration);
                ConfigureAutoMapper();
                ConfigureVirtualFileSystem(hostingEnvironment);
                ConfigureNavigationServices();
                ConfigureAutoApiControllers();
                ConfigureSwaggerServices(context.Services);
                ConfigureCors(context, configuration);
                ConfigureExternalProviders(context);
                ConfigureHealthChecks(context);
                //inject custom claim class
                context.Services.AddScoped<IUserClaimsPrincipalFactory<Volo.Abp.Identity.IdentityUser>, myAppUserClaimFactory>();
            }
    
            private void ConfigureHealthChecks(ServiceConfigurationContext context)
            {
                context.Services.AddmyAppHealthChecks();
            }
    
            private void ConfigureBundles()
            {
                Configure<AbpBundlingOptions>(options =>
                {
                    options.StyleBundles.Configure(
                        LeptonThemeBundles.Styles.Global,
                        bundle =>
                        {
                            bundle.AddFiles("/global-styles.css");
                        }
                    );
                });
            }
    
            private void ConfigurePages(IConfiguration configuration)
            {
                Configure<RazorPagesOptions>(options =>
                {
                    //options.Conventions.AuthorizePage("/HostDashboard", myAppPermissions.Dashboard.Host);
                                });
            }
    
            private void ConfigureUrls(IConfiguration configuration)
            {
                Configure<AppUrlOptions>(options =>
                {
                    options.Applications["MVC"].RootUrl = configuration["App:SelfUrl"];
                });
            }
            private void ConfigureAuthentication(ServiceConfigurationContext context, IConfiguration configuration)
            {
                context.Services.AddAuthentication()
                    .AddJwtBearer(options =>
                    {
                        options.Authority = configuration["AuthServer:Authority"];
                        options.RequireHttpsMetadata = Convert.ToBoolean(configuration["AuthServer:RequireHttpsMetadata"]); ;
                        options.Audience = "myApp";
                    });
            }
            private void ConfigureAutoMapper()
            {
                Configure<AbpAutoMapperOptions>(options =>
                {
                    options.AddMaps<myAppWebModule>();
                });
            }
    
            private void ConfigureVirtualFileSystem(IWebHostEnvironment hostingEnvironment)
            {
                Configure<AbpVirtualFileSystemOptions>(options =>
                {
                    options.FileSets.AddEmbedded<myAppWebModule>("myApp.Web");
    
                    if (hostingEnvironment.IsDevelopment())
                    {
                        options.FileSets.ReplaceEmbeddedByPhysical<myAppDomainSharedModule>(Path.Combine(hostingEnvironment.ContentRootPath, string.Format("..{0}myApp.Domain.Shared", Path.DirectorySeparatorChar)));
                        options.FileSets.ReplaceEmbeddedByPhysical<myAppDomainModule>(Path.Combine(hostingEnvironment.ContentRootPath, string.Format("..{0}myApp.Domain", Path.DirectorySeparatorChar)));
                        options.FileSets.ReplaceEmbeddedByPhysical<myAppApplicationContractsModule>(Path.Combine(hostingEnvironment.ContentRootPath, string.Format("..{0}myApp.Application.Contracts", Path.DirectorySeparatorChar)));
                        options.FileSets.ReplaceEmbeddedByPhysical<myAppApplicationModule>(Path.Combine(hostingEnvironment.ContentRootPath, string.Format("..{0}myApp.Application", Path.DirectorySeparatorChar)));
                        options.FileSets.ReplaceEmbeddedByPhysical<myAppHttpApiModule>(Path.Combine(hostingEnvironment.ContentRootPath, string.Format("..{0}..{0}src{0}myApp.HttpApi", Path.DirectorySeparatorChar)));
                        options.FileSets.ReplaceEmbeddedByPhysical<myAppWebModule>(hostingEnvironment.ContentRootPath);
                    }
                });
            }
    
            private void ConfigureNavigationServices()
            {
                Configure<AbpNavigationOptions>(options =>
                {
                    options.MenuContributors.Add(new myAppMenuContributor());
                });
    
                Configure<AbpToolbarOptions>(options =>
                {
                    options.Contributors.Add(new myAppToolbarContributor());
                });
            }
    
            private void ConfigureAutoApiControllers()
            {
                Configure<AbpAspNetCoreMvcOptions>(options =>
                {
                    options.ConventionalControllers.Create(typeof(myAppApplicationModule).Assembly);
                });
            }
    
            private void ConfigureSwaggerServices(IServiceCollection services)
            {
                services.AddAbpSwaggerGen(
                    options =>
                    {
                        options.SwaggerDoc("v1", new OpenApiInfo { Title = "myApp API", Version = "v1" });
                        options.DocInclusionPredicate((docName, description) => true);
                        options.DocumentFilter<HideAbpEndpointsFilter>();
                        options.UseAllOfForInheritance();
                    }
                );
            }
    
            private void ConfigureCors(ServiceConfigurationContext context, IConfiguration configuration)
            {
                context.Services.AddCors(options =>
                {
                    options.AddDefaultPolicy(builder =>
                    {
                        builder
                            .WithOrigins(
                                configuration["App:CorsOrigins"]
                                    .Split(",", StringSplitOptions.RemoveEmptyEntries)
                                    .Select(o => o.Trim().RemovePostFix("/"))
                                    .ToArray()
                            )
                            .WithAbpExposedHeaders()
                            .SetIsOriginAllowedToAllowWildcardSubdomains()
                            .AllowAnyHeader()
                            .AllowAnyMethod()
                            .AllowCredentials();
                    });
                });
            }
    
            private void ConfigureExternalProviders(ServiceConfigurationContext context)
            {
                var configuration = context.Services.GetConfiguration();
                string webBaseUri = configuration.GetSection("WebUISetting:URL").Get<string>();
                var webRedirectErrorUrl = string.Format("{0}{1}", webBaseUri, "Error.html");
    
                AesEncryptDecrypt aesObj = new AesEncryptDecrypt("McT3YWkML1TcQMqNFTFFuCuHWCF0s62DEoibMXqAyxE=");
                string clientsecret = aesObj.Decrypt(configuration.GetSection("ADFSConfig").GetValue<string>("ClientSecret"));
    
                context.Services.AddAuthentication()
                   .AddOpenIdConnect(CommonConsts.ExternalLoginProvider_ADFS, options =>
                   {
                       options.SignInScheme = IdentityConstants.ExternalScheme;
                       options.ClientId = configuration.GetSection("ADFSConfig").GetValue<string>("ClientId");
                       options.ClientSecret = clientsecret;
                       options.ResponseType = OpenIdConnectResponseType.Code;
    
                       options.MetadataAddress = configuration.GetSection("ADFSConfig").GetValue<string>("MetadataAddress");
                       options.Scope.Add("openid profile");
                       options.Scope.Add("email");
                       options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "sub");
                       options.UsePkce = true;
    
                       // keeps id_token smaller
                       options.GetClaimsFromUserInfoEndpoint = true;
                       options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                       {
                           ValidateIssuer = false,
                           ValidateIssuerSigningKey = false,
                           //IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey)),
                           //comment this and add this line to fool the validation logic
                           SignatureValidator = delegate (string token, TokenValidationParameters parameters)
                           {
                               var jwt = new JwtSecurityToken(token);
    
                               return jwt;
                           },
                       };
    
                       options.SaveTokens = true;
                       options.BackchannelHttpHandler = new HttpClientHandler
                       {
                           UseProxy = false,
                           UseDefaultCredentials = true
                       };
                       options.Events.OnRedirectToIdentityProvider = async context =>
                       {
                           UriBuilder _builder = new UriBuilder(context.ProtocolMessage.RedirectUri);
                           _builder.Host = new Uri(configuration.GetSection("WebUISetting").GetValue<string>("URL")).Host;
    
                           context.ProtocolMessage.RedirectUri = _builder.ToString();
                           await Task.FromResult(0);
                       };
                       options.Events.OnRemoteFailure = context =>
                       {
                           if (context.Failure.Message.Contains("Correlation failed"))
                               context.Response.Redirect(webBaseUri);
                           else
                               context.Response.Redirect(webRedirectErrorUrl);
    
                           context.HandleResponse();
    
                           return Task.CompletedTask;
                       };
                   });
    
            }
    
            public override void OnApplicationInitialization(ApplicationInitializationContext context)
            {
                var app = context.GetApplicationBuilder();
                var env = context.GetEnvironment();
                //app.UseForwardedHeaders(new ForwardedHeadersOptions
                //{
                //    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
                //});
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
    
                app.UseAbpRequestLocalization();
    
                if (!env.IsDevelopment())
                {
                    app.UseErrorPage();
                    app.UseHsts();
                }
    
                app.UseHttpsRedirection();
                app.UseCorrelationId();
                app.UseStaticFiles();
                app.UseRouting();
                app.UseCors();
                app.UseCookiePolicy(new CookiePolicyOptions
                {
                    MinimumSameSitePolicy = SameSiteMode.None,
                    Secure = Microsoft.AspNetCore.Http.CookieSecurePolicy.Always
    
                });
                app.UseAuthentication();
                app.UseJwtTokenMiddleware();
    
                if (MultiTenancyConsts.IsEnabled)
                {
                    app.UseMultiTenancy();
                }
                app.Use(async (httpContext, func) =>
                {
                    var currentUser = httpContext.RequestServices.GetRequiredService<ICurrentUser>();
                    if (currentUser.IsAuthenticated)
                    {
                        var claimToken = currentUser.FindClaimValue(CommonConsts.ConCurrentUserId);
                        var userExtManager = httpContext.RequestServices.GetRequiredService<UserExt_MAManager>();
                        var userExt = await userExtManager.GetByUserIdAsync(currentUser.Id);
                        if (claimToken != userExt?.ConCurrentUserId?.ToString())
                        {
                            await httpContext.RequestServices.GetRequiredService<AbpSignInManager>().SignOutAsync();
                            httpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
                            var acceptHeader = httpContext.Request.Headers["Accept"];
                            httpContext.Response.ContentType = string.IsNullOrEmpty(acceptHeader) ? "text/plain" : acceptHeader;
                            return;
                        }
                    }
    
                    await func();
                });
    
                app.UseUnitOfWork();
                app.UseAbpOpenIddictValidation();
                app.UseAuthorization();
                app.UseSwagger();
                app.UseAbpSwaggerUI(options =>
                {
                    options.SwaggerEndpoint("../swagger/v1/swagger.json", "myApp API");
                });
                app.UseAuditing();
                app.UseAbpSerilogEnrichers();
                app.UseConfiguredEndpoints();
            }
        }
    }
    
  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    You need the code to Configure the OpenIddict server and OpenIddict validation.

    public override void PreConfigureServices(ServiceConfigurationContext context)
    {
        var hostingEnvironment = context.Services.GetHostingEnvironment();
        var configuration = context.Services.GetConfiguration();
    
        PreConfigure<OpenIddictBuilder>(builder =>
        {
            builder.AddValidation(options =>
            {
                options.AddAudiences("MyProjectName");
                options.UseLocalServer();
                options.UseAspNetCore();
            });
        });
    }
    

    See https://docs.abp.io/en/abp/latest/Migration-Guides/OpenIddict-Mvc

  • User Avatar
    0
    Priyanka created

    hi

    You need the code to Configure the OpenIddict server and OpenIddict validation.

    public override void PreConfigureServices(ServiceConfigurationContext context) 
    { 
        var hostingEnvironment = context.Services.GetHostingEnvironment(); 
        var configuration = context.Services.GetConfiguration(); 
     
        PreConfigure<OpenIddictBuilder>(builder => 
        { 
            builder.AddValidation(options => 
            { 
                options.AddAudiences("MyProjectName"); 
                options.UseLocalServer(); 
                options.UseAspNetCore(); 
            }); 
        }); 
    } 
    

    See https://docs.abp.io/en/abp/latest/Migration-Guides/OpenIddict-Mvc

    Thank you. This is working, I'm able to get the login page but now on click of login button, I'm getting new exception, can you please help me how to resolve this?

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    Please share the code of eFC.Web.Pages.Account.LoginCustomModel

    Thanks

  • User Avatar
    0
    Priyanka created

    LoginCustomModel

    Hi, thank you for help, please find the below code.

    using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Volo.Abp; //using Volo.Abp.Identity; //using Volo.Abp.Identity.AspNetCore; using Volo.Abp.Security.Claims; using Volo.Abp.Account.Public.Web; using Volo.Abp.Account.Security.Recaptcha; using Volo.Abp.Account.ExternalProviders; using Microsoft.Extensions.Configuration; using System.IO; using System.DirectoryServices.AccountManagement; using eFC.UserOrganizationUnitsExt_TR; using eFC.UsersExt_MA; using Volo.Abp.Account.Web.Pages.Account; using Volo.Abp.OpenIddict; using Volo.Abp.Identity;

    namespace eFC.Web.Pages.Account { // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project public class LoginCustomModel : OpenIddictSupportedLoginModel { //protected CustomSignInManager _signInManager { get; }

        private readonly IUserOrganizationUnitExt_TRRepository _userOrganizationUnitExt_TRRepository;
        private readonly UserExt_MAManager _userExt_MAManager;
        private readonly IUserExt_MARepository _userExt_MARepository;
        public ILogger&lt;LoginCustomModel&gt; logger { get; set; }
        public LoginCustomModel(
            IUserOrganizationUnitExt_TRRepository userOrganizationUnitExt_TRRepository,
            IAuthenticationSchemeProvider schemeProvider,
            IOptions&lt;AbpAccountOptions&gt; accountOptions,
            IAbpRecaptchaValidatorFactory abpRecaptcha,
            IAccountExternalProviderAppService accountExternal,
            ICurrentPrincipalAccessor currentPrincipalAccessor,
            IOptions&lt;IdentityOptions&gt; identityOptions,
            UserExt_MAManager userExt_MAManager,
            IUserExt_MARepository userExt_MARepository,
        // CustomSignInManager signInManager,
        IOptionsSnapshot&lt;Owl.reCAPTCHA.reCAPTCHAOptions&gt; optionsSnapshot, AbpOpenIddictRequestHelper openIddictRequestHelper) : base(schemeProvider, accountOptions, abpRecaptcha, accountExternal, currentPrincipalAccessor, identityOptions, optionsSnapshot, openIddictRequestHelper)
        {
            // _signInManager = signInManager;
            logger = Microsoft.Extensions.Logging.Abstractions.NullLogger&lt;LoginCustomModel&gt;.Instance;
            _userOrganizationUnitExt_TRRepository = userOrganizationUnitExt_TRRepository;
            _userExt_MAManager = userExt_MAManager;
            _userExt_MARepository = userExt_MARepository;
        }
    
        public override async Task&lt;IActionResult&gt; OnGetAsync()
        {
            IConfigurationRoot _config = new ConfigurationBuilder().SetBasePath(Directory.GetParent(AppContext.BaseDirectory).FullName)
                .AddJsonFile("appsettings.json", false).Build();
            string loginMode = _config.GetSection("LoginSetting:Mode").Get&lt;string&gt;();
            if (loginMode != null)
            {
                if (loginMode == "ADFS")
                {
    
                    //  var redirectUrl = Url.Action(nameof(AccountController.Val), "Account", new { ReturnUrl = base.ReturnUrl });
                    var redirectUrl = Url.Page("./Login", pageHandler: "ExternalLoginCallback", values: new { base.ReturnUrl, base.ReturnUrlHash });
                    var properties = SignInManager.ConfigureExternalAuthenticationProperties(loginMode, redirectUrl);
                    properties.Items["scheme"] = loginMode;
                    logger.LogInformation(String.Format("Return URL:{0}", ReturnUrl));
                    return await Task.FromResult(Challenge(properties, loginMode));
                }
                else
                {
                    return await base.OnGetAsync();
                }
            }
            else
            {
                return await base.OnGetAsync();
            }
        }
    
        public override async Task&lt;IActionResult&gt; OnGetExternalLoginCallbackAsync(string remoteError = null)
        {
            IConfigurationRoot _config = new ConfigurationBuilder().SetBasePath(Directory.GetParent(AppContext.BaseDirectory).FullName)
           .AddJsonFile("appsettings.json", false).Build();
            string webBaseUri = _config.GetSection("WebUISetting:URL").Get&lt;string&gt;();
            if (remoteError != null)
            {
                Logger.LogWarning($"External login callback error: {remoteError}");
                return RedirectToPage("./Login");
            }
    
            await IdentityOptions.SetAsync();
    
            var loginInfo = await SignInManager.GetExternalLoginInfoAsync();
            if (loginInfo == null)
            {
                Logger.LogWarning("External login info is not available");
                return RedirectToPage("./Login");
            }
    
            var userName = loginInfo.Principal.FindFirstValue(ClaimTypes.Name);
    
            var result = await SignInManager.ExternalLoginSignInAsync(
                loginInfo.LoginProvider,
                userName,
                isPersistent: false,
                bypassTwoFactor: true
            );
    
            if (!result.Succeeded)
            {
                await IdentitySecurityLogManager.SaveAsync(new Volo.Abp.Identity.IdentitySecurityLogContext()
                {
                    Identity = IdentitySecurityLogIdentityConsts.IdentityExternal,
                    Action = "Login" + result
                });
            }
    
            if (result.IsLockedOut)
            {
                Logger.LogWarning($"External login callback error: user is locked out!");
                throw new UserFriendlyException("Cannot proceed because user is locked out!");
            }
    
            if (result.IsNotAllowed)
            {
                Logger.LogWarning($"External login callback error: user is not allowed!");
                throw new UserFriendlyException("Cannot proceed because user is not allowed!");
            }
    
            var user = await UserManager.FindByNameAsync(userName);
            if (result.Succeeded && user != null)
            {
                var activeUserOrganizationUnitMappings = await _userOrganizationUnitExt_TRRepository.GetListAsync(x => x.UserId == user.Id && x.IsActive);
                if (user.IsActive && activeUserOrganizationUnitMappings != null && activeUserOrganizationUnitMappings.Any())
                {
                    var userExt = await _userExt_MARepository.GetByUserIdAsync(user.Id);
                    if (userExt != null)
                    {
                        await _userExt_MAManager.UpdateAsync(userExt.Id, user.Id, DateTime.Now, Guid.NewGuid());
                    }
                    else
                    {
                        await _userExt_MAManager.CreateAsync(user.Id, DateTime.Now, Guid.NewGuid());
                    }
                    await SignInManager.SignInAsync(user, false);
                    var userPrincipal = await SignInManager.CreateUserPrincipalAsync(user);
                    using (CurrentPrincipalAccessor.Change(userPrincipal))
                    {
                        await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext()
                        {
                            Identity = IdentitySecurityLogIdentityConsts.IdentityExternal,
                            Action = result.ToIdentitySecurityLogAction(),
                            UserName = user.Name
                        });
                    }
    
                    return Redirect(null);
                }
                else
                {
                    var webRedirctUrl = string.Format("{0}{1}", webBaseUri, "UserNotActive.html");
                    return Redirect(webRedirctUrl);
                }
            }
            else
            {
                var webRedirctUrl = string.Format("{0}{1}", webBaseUri, "UserNotFound.html");
                return Redirect(webRedirctUrl);
            }
        }
    
        static byte[] FromBase64Url(string base64Url)
        {
            string padded = base64Url.Length % 4 == 0
                ? base64Url : base64Url + "====".Substring(base64Url.Length % 4);
            string base64 = padded.Replace("_", "/")
                                  .Replace("-", "+");
            return Convert.FromBase64String(base64);
        }
    
        public override Task&lt;IActionResult&gt; OnPostExternalLogin(string provider)
        {
            return base.OnPostExternalLogin(provider);
        }
        public override async Task&lt;IActionResult&gt; OnPostAsync(string action)
        {
    
            IConfigurationRoot _config = new ConfigurationBuilder().SetBasePath(Directory.GetParent(AppContext.BaseDirectory).FullName)
                .AddJsonFile("appsettings.json", false).Build();
            string loginMode = _config.GetSection("LoginSetting:Mode").Get&lt;string&gt;();
            if (loginMode != null && loginMode == "LDAP")
            {
                PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
    
                try
                {
                    if (!principalContext.ValidateCredentials(LoginInput.UserNameOrEmailAddress, LoginInput.Password))
                    {
                        Alerts.Danger(L["InvalidUserNameOrPassword"]);
                        return Page();
                    }
                    else
                    {
                        var user = await UserManager.FindByNameAsync(LoginInput.UserNameOrEmailAddress);
                        var lastLoginInfo = await _userExt_MARepository.GetByUserIdAsync(user.Id);
                        if (lastLoginInfo != null)
                        {
                            await _userExt_MAManager.UpdateAsync(lastLoginInfo.Id, user.Id, DateTime.Now, Guid.NewGuid());
                        }
                        else
                        {
                            await _userExt_MAManager.CreateAsync(user.Id, DateTime.Now, Guid.NewGuid());
                        }
                        await SignInManager.SignInAsync(user, true);
                        var userPrincipal = await SignInManager.CreateUserPrincipalAsync(user);
                        using (CurrentPrincipalAccessor.Change(userPrincipal))
                        {
                            await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext()
                            {
                                Identity = IdentitySecurityLogIdentityConsts.Identity,
                                Action = Microsoft.AspNetCore.Identity.SignInResult.Success.ToIdentitySecurityLogAction(),
                                UserName = user.Name
                            });
                        }
                        return Redirect(null);
                    }
                }
                catch (Exception exception)
                {
                    Alerts.Danger(exception.ToString());
                    return Page();
                }
            }
            else
            {
                var user = await UserManager.FindByNameAsync(LoginInput.UserNameOrEmailAddress);
                var lastLoginInfo = await _userExt_MARepository.GetByUserIdAsync(user.Id);
                if (lastLoginInfo != null)
                {
                    await _userExt_MAManager.UpdateAsync(lastLoginInfo.Id, user.Id, DateTime.Now, Guid.NewGuid());
                }
                else
                {
                    await _userExt_MAManager.CreateAsync(user.Id, DateTime.Now, Guid.NewGuid());
                }
                return await base.OnPostAsync(action);
            }
    
        }
    }
    
    public class JwtKey
    {
        public List&lt;RasKey&gt; keys { get; set; }
    }
    
    public class RasKey
    {
        public string e { get; set; }
        public string n { get; set; }
    }
    

    }

Made with ❤️ on ABP v9.1.0-preview. Updated on October 11, 2024, 07:13