Giter Site home page Giter Site logo

vahidn / dntidentity Goto Github PK

View Code? Open in Web Editor NEW
260.0 27.0 95.0 3.75 MB

A highly customized sample of the ASP.NET Core Identity

License: Apache License 2.0

C# 74.10% Batchfile 0.31% CSS 0.42% PowerShell 7.01% JavaScript 2.04% HTML 16.12% Smalltalk 0.01%
aspnetcore aspnetcoreidentity efcore entityframework entity-framework entity-framework-core aspnet-core persian asp-net-core-identity

dntidentity's People

Contributors

aminmesbahi avatar vahidn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dntidentity's Issues

Error when upgrade DNTCommon.Web.Core 2.0.0 to 2.1.0

when upgrade my project dependency and apply changes, show below error

An unhandled exception occurred while processing the request.
ArgumentNullException: context (Parameter 'Value cannot be null or empty.')
Microsoft.AspNetCore.Mvc.Routing.UrlHelperFactory.GetUrlHelper(ActionContext context)

Stack Query Cookies Headers Routing
ArgumentNullException: context (Parameter 'Value cannot be null or empty.')
Microsoft.AspNetCore.Mvc.Routing.UrlHelperFactory.GetUrlHelper(ActionContext context)
DNTCommon.Web.Core.HttpRequestInfoServiceExtensions+<>c.b__0_0(IServiceProvider serviceProvider)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor<TArgument, TResult>.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor<TArgument, TResult>.VisitCallSite(ServiceCallSite callSite, TArgument argument)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine+<>c__DisplayClass1_0.b__0(ServiceProviderEngineScope scope)
Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider)
DNTCommon.Web.Core.HttpRequestExtensions.GetUrlHelper(HttpContext httpContext)
DNTCommon.Web.Core.HttpRequestExtensions.GetActionUrl(HttpContext httpContext, string action, string controller)
DNTCommon.Web.Core.ContentSecurityPolicyMiddleware.Invoke(HttpContext context, IOptionsSnapshot config)
Microsoft.AspNetCore.Builder.UseMiddlewareExtensions+<>c__DisplayClass4_1.b__2(HttpContext context)
Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.HandleException(HttpContext context, ExceptionDispatchInfo edi)
Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

حذف متد CheckArgumentIsNull

سلام
ممنون بابت مثال کاربردی که ارائه کردید.
دلیل حذف این متد در ورژن جدید چیه؟ چون الان در همه متدهای سازنده باید بررسی نال بودن انجام بشه...

public static void CheckArgumentIsNull(this object o, string name)
{
    if (o == null)
        throw new ArgumentNullException(name);
}

اگر متد زیر رو داشته باشیم کمکی میکنه؟

public static T CheckArgument<T>(this T obj)
{
    return obj ?? throw new ArgumentNullException(typeof(T).Name);
}
public LoginController(IApplicationSignInManager signInManager)
{
    _signInManager = signInManager.CheckArgument();
}

grid sample

با سلام و تشکر فراوان بابت به اشتراک گذاری پروژه
میخواستم اگر براتون مقدور هست یک سمپل گرید ساده هم به پروژه اضافه بفرمایید مثلا برای محصولات که موجودیت ها و سرویس هاش هم موجود هست
با تشکر

Controllers

Hello.
I Suggest you to create controller project separated from UI layer.
And add folder solution for categorized projects.
very tanks.

ioc configin in WCF service application

سلام آقای نصیری
من یک پروژه WCF Service Application به سولوشن اضافه کردم، میخواستم بدونم چطور میتونم به ApplicationDbContext دسترسی داشته باشم ، آیا امکان استفاده از IocConfig برای تزریق وابستگی ها توی پروژه Wcf Service هست ؟
من از Windosr استفاده کردم و به کانستراکتور سرویسم IUnitOfWork را اضافه کردم اما وابستگی
Ef Core رو چطور باید در این پروژه انجام بدم؟
پیشاپیش خیلی از راهنماییتون متشکرم

Exception has occurred: CLR/System.InvalidOperationException

image

after run by vscode :
Exception has occurred: CLR/System.InvalidOperationException
An exception of type 'System.InvalidOperationException' occurred in Microsoft.EntityFrameworkCore.Relational.dll but was not handled in user code: 'Relational-specific methods can only be used when the context is using a relational database provider.'
at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.GetRelationalService[TService](IInfrastructure`1 databaseFacade)
at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate(DatabaseFacade databaseFacade)
at ASPNETCoreIdentitySample.Services.Identity.IdentityDbInitializer.Initialize() in E:\Projects\DNTIdentity\src\ASPNETCoreIdentitySample.Services\Identity\IdentityDbInitializer.cs:line 64
at ASPNETCoreIdentitySample.IocConfig.IdentityServicesRegistry.callDbInitializer(IApplicationBuilder app) in E:\Projects\DNTIdentity\src\ASPNETCoreIdentitySample.IocConfig\IdentityServicesRegistry.cs:line 40
at ASPNETCoreIdentitySample.IocConfig.IdentityServicesRegistry.UseCustomIdentityServices(IApplicationBuilder app) in E:\Projects\DNTIdentity\src\ASPNETCoreIdentitySample.IocConfig\IdentityServicesRegistry.cs:line 31
at ASPNETCoreIdentitySample.Startup.Configure(ILoggerFactory loggerFactory, IApplicationBuilder app, IHostingEnvironment env) in E:\Projects\DNTIdentity\src\ASPNETCoreIdentitySample\Startup.cs:line 83

Don't Show ModelState Errors in _PartialView

I Create two method (Render, Edit,Create) as Partial :

[AjaxOnly]
        public async Task<IActionResult> Render([FromBody]ModelIdViewModel modelvm)
        {
            var zones = AutoMapper.Mapper.Map(_siteOptions.Value.EducationallevelOfTheCeoes, new List<SelectListItem>());
            var modelVm = new RateViewModel { EducationallevelOfTheCeoes = zones };
            if (string.IsNullOrWhiteSpace(modelvm?.Id))
            {
                return PartialView("_Create", modelVm);
            }

            var model = await _rateService.FindByIdAsync(Convert.ToInt32(modelvm.Id)).ConfigureAwait(false);
            if (model == null)
            {
                ModelState.AddModelError("", NotFound);
                return PartialView("_Create");
            }
            AutoMapper.Mapper.Map(model, modelVm);
            var selectItems = modelVm.EducationallevelOfTheCeoes.Select(s => new SelectListItem
            {
                Text = s.Text,
                Value = s.Value,
                Selected = s.Value == model.EducationallevelOfTheCeoId.ToString()
            });
            modelVm.EducationallevelOfTheCeoes = selectItems.ToList();
            return PartialView("_Create", model: modelVm);
        }

        [AjaxOnly]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(RateViewModel modelvm)
        {
            if (ModelState.IsValid)
            {
                    var result = await _rateService.UpdateAsync(modelvm);
                    if (result.Succeeded)
                    {
                        return Json(new { success = true });
                    }
                    ModelState.AddErrorsFromResult(result);
            }
            return PartialView("_Create", model: modelvm);
        }

and Create _PartialViews by this link

but when send and response erorrs : i don't see in any alert (partial)

logging

سلام آقای نصیری
توی این پروژه شما از logging استفاده کردیدولی چطور میشه اون رو طوری کانفیگ کرد که
LogLevel.Information هم ثبت کنه
الان با تغییر توی startup.cs پروژه خطا میده

مدیریت لاگ

جناب نصیری سوالی داشتم
من لاگ رو براساس مستندات این پروژه پیاده سازی کردم
مشکلی که الان به وجود اومده هر لحظه در جدول لاگ این رکوردها ذخیره میشه و باعث کند شدن سیستم میشه
Log.txt

1 2019-06-16 00:03:14.6550548 10403   Information Microsoft.EntityFrameworkCore.Infrastructure Entity Framework Core 2.2.4-servicing-10062 initialized 'ApplicationDbContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: MaxPoolSize=128 CommandTimeout=180 using NetTopologySuite [  {    "Key": "version",    "Value": "2.2.4-servicing-10062"  },  {    "Key": "contextType",    "Value": "ApplicationDbContext"  },  {    "Key": "provider",    "Value": "Microsoft.EntityFrameworkCore.SqlServer"  },  {    "Key": "options",    "Value": "MaxPoolSize=128 CommandTimeout=180 using NetTopologySuite "  },  {    "Key": "{OriginalFormat}",    "Value": "Entity Framework Core {version} initialized '{contextType}' using provider '{provider}' with options: {options}"  }] NULL NULL 2019-06-15 19:33:16.7030948 +00:00 NULL NULL NULL

ممنون میشم راهنمایی کنید

English version

Hi I was looking for the english version, also you mentioned an EPP plus ASP mvc sample, can you please point me to that.

thanks

SecurityStampValidator Not Run

سلام جناب نصیری

من از ساختار پروژه شما استفاده کردم اما وارد این بخش نمی شود
تمام روال ها رو بررسی کردم از تزریق وابستگی ها تا خود پیاده سازی کلاس ها دقیقا مثل شما هست
اما در پروژه خودم وارد این بخش نمی شود تا آخرین ورود کاربر رو ذخیره کند.
ممنون میشم راهنمایی کنید

Exeption : ViewRendererService.cs in .Common When Use in HangFire.Core

Hi

I use ViewRendererService.cs With Hangfire.Core (Background Jobs Manager)

public async Task JobSample(SampleEmailModel emailModelVm)
{
await _viewRendererService.RenderViewToStringAsync("~/Areas/Management/Views/EmailTemplates/_SendEmail.cshtml", emailModelVm).ConfigureAwait(false);
}

and send method to hangfire as a job :

var emailModelVm= new SampleEmailModel();
BackgroundJob.Enqueue(() => JobSample(emailModelVm));

i have below Exeption in this line :

image

(send a view path (view without or with model) no change result)

عدم نمایش ظاهر سایت

با سلام
سپاسگزارم از شما بایت اشتراک گذاری این پروژه
ببخشید شاید سوالم ابتدایی باشه ولی وقتی که این پروژه رو اجرا میکنم انگار که فایل های
css
به درستی لود نمیشن و ظاهر سایت به خوبی نمایش داده نمیشه
ممنون میشم بنده رو راهنمایی بفرمائید

how to remove email from identity

Hi,
I dont need email in my register so I want to know how can I remove email from register?
even when I removed validateEmail method from ValidateAsync method, I get InvalidEmail when I dont have email in my form from?

authorization in razor code

عرض سلام و ادب احترام جهت اعمال دسترسی در بین کدهای کندو نیاز به استفاده از کدی همانند
User.Identity.IsInrole("SomeRole")
دارم با تگی که شما گذاشتید نمیشه این کارو انجام داد ایا میشه توسط همچین کدی کنترلر و اکشن رو فرستاد و با یک
if
ساده چک کرد
باتشکر

CspReportController The JSON value could not be converted to System.String

Summary of the issue

I got an error when I am trying to register a user.

Environment

.NET Core SDK version: 3.1.201
IDE: VS 2019 16.6.1

Example code/Steps to reproduce:

I just downloaded the source code from the repository, changed ActiveDatabase to InMemoryDatabase, and ran the project.

  "ActiveDatabase": "InMemoryDatabase", 

Output:

1

2

info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[3]
      Route matched with {action = "Log", controller = "CspReport", area = ""}. Executing controller action with signature System.Threading.Tasks.Task`1[Microsoft.AspNetCore.Mvc.IActionResult] Log() on controller ASPNETCoreIdentitySample.Controllers.CspReportController (ASPNETCoreIdentitySample).
fail: ASPNETCoreIdentitySample.Controllers.CspReportController[0]
      Content Security Policy Error: {"csp-report":{"document-uri":"https://localhost:5001/Identity/Register","referrer":"https://localhost:5001/Identity/Register","violated-directive":"font-src","effective-directive":"font-src","original-policy":"default-src 'self' blob:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval' ; font-src 'self'; img-src 'self' data: blob:; connect-src 'self'; media-src 'self'; object-src 'self' blob:; report-uri /api/CspReport/Log","disposition":"enforce","blocked-uri":"data","status-code":0,"script-sample":""}}
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]
      Executed action ASPNETCoreIdentitySample.Controllers.CspReportController.Log (ASPNETCoreIdentitySample) in 1.4908ms
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
      Executed endpoint 'ASPNETCoreIdentitySample.Controllers.CspReportController.Log (ASPNETCoreIdentitySample)'
fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[1]
      An unhandled exception has occurred while executing the request.
System.Text.Json.JsonException: The JSON value could not be converted to System.String. Path: $.csp-report.status-code | LineNumber: 0 | BytePositionInLine: 520.
 ---> System.InvalidOperationException: Cannot get the value of a token type 'Number' as a string.
   at System.Text.Json.Utf8JsonReader.GetString()
   at System.Text.Json.Serialization.Converters.JsonConverterString.Read(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options)
   at System.Text.Json.JsonPropertyInfoNotNullable`4.OnRead(ReadStack& state, Utf8JsonReader& reader)
   at System.Text.Json.JsonPropertyInfo.Read(JsonTokenType tokenType, ReadStack& state, Utf8JsonReader& reader)
   at System.Text.Json.JsonSerializer.ReadCore(JsonSerializerOptions options, Utf8JsonReader& reader, ReadStack& readStack)
   --- End of inner exception stack trace ---
   at System.Text.Json.ThrowHelper.ReThrowWithPath(ReadStack& readStack, Utf8JsonReader& reader, Exception ex)
   at System.Text.Json.JsonSerializer.ReadCore(JsonSerializerOptions options, Utf8JsonReader& reader, ReadStack& readStack)
   at System.Text.Json.JsonSerializer.ReadCore(Type returnType, JsonSerializerOptions options, Utf8JsonReader& reader)
   at System.Text.Json.JsonSerializer.Deserialize(String json, Type returnType, JsonSerializerOptions options)
   at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, JsonSerializerOptions options)
   at ASPNETCoreIdentitySample.Controllers.CspReportController.Log() in C:\Users\0084125561\Desktop\DNTIdentity-master\src\ASPNETCoreIdentitySample\Controllers\CspReportController.cs:line 97
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]

Did I miss something?

DNTCaptcha in V 3.1.100.1398.09.17

سلام
آخرین ورژن(3.1.100.1398.09.17) را دریافت کردم ولی
DNTCaptcha
از کار افتاده است
آیا تنظیماتی رو از قلم انداخته ام؟

migration fails

عرض ادب
بعد از به روز رسانی به نسخه 2017 امکان ایجاد یا به روز رسانی مایگریشن وجود نداره
خطا:
D:\DNTIdentity-master\src\ASPNETCoreIdentitySample\obj\ASPNETCoreIdentitySample.csproj.EntityFrameworkCore.targets(4,5): error MSB4006: There is a circular dependency in the target dependency graph involving target "GetEFProjectMetadata". [D:\DNTIdentity-master\src\ASPNETCoreIdentitySample\ASPNETCoreIdentitySample.csproj] Unable to retrieve project metadata. Ensure it's an MSBuild-based .NET Core project. If you're using custom BaseIntermediateOutputPath or MSBuildProjectExtensionsPath values, Use the --msbuildprojectextensionspath option.

BundlerMinifier problem

مشکلی که گزارش دادم مربوط به بسته ناگت شما بود که به روز نشده بود و با گرفتن این کامیت مشکلی وجود نداشت با تشکر
فقط بنده به هرشکل تلاش میکنم نمیتونم تو سایت شما عضو بشم هرچقدرم ایمیل میزارم جوابی نمیدین

Login status lost

تمامی قسمت هارو درست کار میکنن ولی وقتی اپلیکیشن پول خالی میشه یا خود IIS ریست میشه تمامی یوز پسورد ها از بین میره . این مورد وقتی یوزر هامون زیاده داره اذیت میکنه با توجه به اینکه من سیستم ورود رو با پیامک گذاشتم هزینه هم داره برای من زیاد میشه . ممکنه بفرمایید مشکل از کجاست ؟ سرور ویندوز 2016 هست و ازهمین پروژه استفاده شده make-cert رو انجام دادم ولی بازم از بین میره لوگین کاربرا

اشکال در تنظیم سطوح دسترسی پویا

سلام
تشکر بابت پروژه خیلی خوبتون
در قسمت اختصاص دسترسی به نقش ها موقع افزودن دسترسی نقش به اکشن متدها مشکلی وجود نداره ولی اگه بخوایم تمامی دسترسی هایی رو که به یک نقش دادیم از آن نقش بگیریم امکان پذیر نیست در حالی که پیغام موفقیت آمیز بودن عملیات رو هم نشون میده.
اگه یکی یکی دسترسی ها رو بگیریم و ذخیره کنیم باز حداقل یک دسترسی باقی می ماند.

.NET 5 and Template

Thanks for such a useful project.

Does this project support .NET 5?
Is there any project template powered by this project?

بررسی مجدد بخش ثبت نام در پروژه

با سلام . در هنگام ثبت نام وقتی نام کاربری درج میشود و هنوز ایمیلی وارد نشده است پیام خطای ولیدیشن ایمیل را میدهد و به نظر بنده این بخش نیاز به ویرایش دارد .
firefox_2018-03-04_00-31-25

خطا در صفحه مدیریت کاربران پس از ارتقاء به نسخه netcore2.2

با سلام
پس از ارتقاء نسخه دات نت در صفحه مدیریت کاربران -قسمت صفحه بندی خطا بوجود میاد
/identity/usersmanager

<cs-pager cs-paging-pagesize ...

System.NullReferenceException: Object reference not set to an instance of an object
at cloudscribe.Web.Pagination.PagerTagHelper.Process(TagHelperContext context, TagHelperOutput output)

   at Microsoft.AspNetCore.Razor.TagHelpers.TagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)

   at Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.RunAsync(TagHelperExecutionContext executionContext)


عدم سرو شدن فایل های استاتیک زمان پابلیش

سلام
فایل های استاتیک من در زمان دولوپ مشکلی ندارن و همه سرو میشن ولی وقتی پابلیش میکنم دیگه فایل های استاتیک سرو نمیشن و خطای 410 داده میشه و اونها رو پیدا نمیکنه.

همین طور من به جای
bower.json
اومدم از
package.json
هم استفاده کردم و دستور
npm i
رو زدم و بعد
bundleconfig.json
رو بر مبنای
node_modules
به روز کردم و در نهایت هم

app.UseFileServer(new FileServerOptions
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "bower_components")),
                RequestPath = "/bower_components",
                EnableDirectoryBrowsing = false
            });

رو به

app.UseFileServer(new FileServerOptions
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")),
                RequestPath = "/wwwroot",
                EnableDirectoryBrowsing = false
            });

تغییر دادم چون اگر از

   RequestPath = "/bower_components",

یا

   RequestPath = "/node_modules",

استفاده میکردم زمان پابلیش خطا میداد که فولدر وجود نداره

ولی در این 2 حالت هم باز فایل های استاتیک سرو نمیشن

افزودن پروایدر Sms برای TFA

سلام جناب نصیری توی این پروژه میخواستم پروایدر SMS رو اضافه کنم برای تایید 2 عاملی این پروایدر رو در چه بخشی باید register کنم؟ سپاس از شما

عوض کردن پوشه bower component

سلام جناب نصیری
ابتدا بابت این پروژه که به اشتراک گذاشتید ازتون قدردانی میکنم

یه سوال
چطوری باید مسیر نصب کامپوننت های
bower
روی عوض کنم و تنظیمش کنم
چون وقتی آپدیت میکنم
خودش میره توی پوشه
wwroot
نصب میشه

ممنون بازم

Coretests

سلام توی لایه تست
قسمت coretests با database provider
مشکل داره آیا باید تغییری داد

دسترسی به اکشن متدهای لوکاپ در حالت استفاده از سیاست سطح دسترسی پویا

با سلام
من طبق مقالاتی که شما در سایت خودتان قرار دادید از سیاست سطح دسترسی پویا استفاده کردم و بسیار کاربردی و عالی بود.
اما تنها مشکل زمانی هست که در یک ویو متعلق به یک کنترلر خاص نیاز هست به اکشن متد خاصی مربوط به یک کنترلر دیگر که کاربر جاری به آن کنترلر دسترسی ندارد دسترسی داشت .
به عنوان مثال یکسری اکشن متد در کنترلرهای مختلف وجود دارد برای پر کردن دراپ داون که در هر جایی مورد استفاده قرار می گیرد
در این حالت مهم اینست که کاربر فقط لاگین کرده باشد و نیاز به پرمیژن خاصی ندارد

من برای حل این مشکل یک پالیسی جدید تعریف کردم و در هندلر مربوط به پالیسی کنترل سطح دسترسی پویا چک میکنم در صورتی که اکشن مربوطه مزین به این پالیسی خاص باشد فقط کافیست که اهراز هویت شود و دسترسی آن را چک نمیکنم.
آیا این روش با توجه به فریمورکی که شما تهیه کرده اید ایراد دارد و یا اینکه روش جایگزینی به غیر از ایجاد یک کنترلر جدا مخصوص دراپ داونها وجود دارد؟

کدهای من به صورت زیر است:

    public class OnlyAuthenticateNeededAndSkipDynamicPermissionRequirement : IAuthorizationRequirement
    {
    }

    public class OnlyAuthenticateNeededAndSkipDynamicPermissionRequirementHandler : AuthorizationHandler<OnlyAuthenticateNeededAndSkipDynamicPermissionRequirement>
    {
        private readonly HttpContext _httpContext;
        private readonly IHttpContextAccessor _httpContextAccessor;

        public OnlyAuthenticateNeededAndSkipDynamicPermissionRequirementHandler(
            IHttpContextAccessor httpContextAccessor,
            IMvcActionsDiscoveryService mvcActionsDiscoveryService)
        {
            _httpContextAccessor = httpContextAccessor;
            _httpContextAccessor.CheckArgumentIsNull(nameof(_httpContextAccessor));

            _httpContext = _httpContextAccessor.HttpContext;
        }

        protected override async Task HandleRequirementAsync(
             AuthorizationHandlerContext context,
             OnlyAuthenticateNeededAndSkipDynamicPermissionRequirement requirement)
        {
            var mvcContext = context.Resource as AuthorizationFilterContext;
            if (mvcContext == null)
            {
                return;
            }

            var actionDescriptor = mvcContext.ActionDescriptor;

            var request = mvcContext.HttpContext.Request;

            if (this?._httpContext?.User?.Identity?.IsAuthenticated == true)
            {
                context.Succeed(requirement);
            }
            else
            {
                context.Fail();
            }
        }
    }

تغییر داده شده در سیاست سطح دسترسی پویا:

        protected override async Task HandleRequirementAsync(
             AuthorizationHandlerContext context,
             DynamicPermissionRequirement requirement)
        {
            var mvcContext = context.Resource as AuthorizationFilterContext;
            if (mvcContext == null)
            {
                return;
            }

            var actionDescriptor = mvcContext.ActionDescriptor;

            var onlyAuthenticateNeeded = actionDescriptor.FilterDescriptors.Select(c => c.Filter).OfType<Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter>().Where(c => c.Policy.Requirements.Any(cc=>cc as OnlyAuthenticateNeededAndSkipDynamicPermissionRequirement != null)).Count() > 0;  //Added
            

            //new System.Collections.Generic.Mscorlib_CollectionDebugView<string>(((Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter)(new System.Linq.SystemCore_EnumerableDebugView<Microsoft.AspNetCore.Mvc.Filters.IFilterMetadata>(actionDescriptor.FilterDescriptors.Select(c => c.Filter)).Items[4])).Policy.AuthenticationSchemes).Items[0];

            var area = actionDescriptor.RouteValues["area"];
            var controller = actionDescriptor.RouteValues["controller"];
            var action = actionDescriptor.RouteValues["action"];

            // How to access form values from an AuthorizationHandler
            var request = mvcContext.HttpContext.Request;
            if (request.Method.Equals("post", StringComparison.OrdinalIgnoreCase))
            {
                if (request.IsAjaxRequest() && request.ContentType.Contains("application/json"))
                {
                    var model = await request.DeserializeJsonBodyAsAsync<RoleViewModel>().ConfigureAwait(false);
                    if (model != null)
                    {

                    }
                }
                else
                {
                    foreach (var item in request.Form)
                    {
                        var formField = item.Key;
                        var formFieldValue = item.Value;
                    }
                }
            }

            if (_securityTrimmingService.CanCurrentUserAccess(area, controller, action , onlyAuthenticateNeeded))
            {
                context.Succeed(requirement);
            }
            else
            {
                context.Fail();
            }
        }

        public bool CanCurrentUserAccess(string area, string controller, string action, bool onlyAuthenticateNeeded = false) //Changed
        {
            return _httpContext != null && CanUserAccess(_httpContext.User, area, controller, action , onlyAuthenticateNeeded);
        }

        public bool CanUserAccess(ClaimsPrincipal user, string area, string controller, string action ,bool onlyAuthenticateNeeded = false)
        {
            var currentClaimValue = $"{area}:{controller}:{action}";
            var securedControllerActions = _mvcActionsDiscoveryService.GetAllSecuredControllerActionsWithPolicy(ConstantPolicies.DynamicPermission);
            if (!securedControllerActions.SelectMany(x => x.MvcActions).Any(x => x.ActionId == currentClaimValue))
            {
                throw new KeyNotFoundException($@"The `secured` area={area}/controller={controller}/action={action} with `ConstantPolicies.DynamicPermission` policy not found. Please check you have entered the area/controller/action names correctly and also it's decorated with the correct security policy.");
            }

            if (!user.Identity.IsAuthenticated)
            {
                return false;
            }

            if(user.Identity.IsAuthenticated && onlyAuthenticateNeeded) //Added
            {
                return true;
            }

            if (user.IsInRole(ConstantRoles.Admin))
            {
                // Admin users have access to all of the pages.
                return true;
            }

            // Check for dynamic permissions
            // A user gets its permissions claims from the `ApplicationClaimsPrincipalFactory` class automatically and it includes the role claims too.
            return user.HasClaim(claim => claim.Type == ConstantPolicies.DynamicPermissionClaimType &&
                                          claim.Value == currentClaimValue);
        }

Sending Json instead of Form Data in DynamicPermission

سلام این کد اجرا میشه و مشکلی ندارم.

 [HttpPost]
        [Authorize(Policy = ConstantPolicies.DynamicPermission)]
        [ActionName("Test")]
        public ActionResult Test([FromForm] string model)
        {
            return Json("ok");
        }

چطور میشه به جای ارسال فرم دیتا، جیسن ارسال کرد ؟

 [HttpPost]
        [Authorize(Policy = ConstantPolicies.DynamicPermission)]
        [ActionName("Test")]
        public ActionResult Test([FromBody] string model)
        {
            return Json("ok");
        }

وقتی جیسن ارسال میکنم این ارور رو بهم میده :

An unhandled exception occurred while processing the request
InvalidOperationException: Incorrect Content-Type: application/json
Microsoft.AspNetCore.Http.Features.FormFeature.ReadForm()

implement SSO

#Question
I am trying to implement SSO by sharing cookies between two .net core apps. it's possible ? Can you help me?

امکان لاگین به جای کاربر دیگر

سلام
اگر ممکن هست امکان لاگین مدیر به جای کاربران دیگر و بازگشت به پنل خودش را به پروژه اضافه کنید.
یا اگر امکان داره راهنمایی بفرمایید، تا در توسعه این قسمت مشارکت کنیم.
با تشکر

اشکال در سطوح دسترسی با استفاده از کاربر ویندوز

با سلام
ضمن تشکر از پروژه عالی شما ، در رابطه با اعتبار سنجی با استفاده از کاربر ویندوز ، من یک یوزر با نام کابر ویندوزم ایجاد کردم و همچنین نقش ادمین رو هم به این یوزر دادم.
در حالتی که من بدون استفاده از فرم لاگین از سیستم استفاده می کنم با پیغام عدم دسترسی به فرم مربوطه مواجه میشوم در حالیکه کاربر من ادمین هست.
طبق بررسی که انجام دادم متوجه شدم که در کانتکست
RoleClaimType
مقدار زیر را دارد:
http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid

در صورتی که مقادیر نقش ها با کلید
http://schemas.microsoft.com/ws/2008/06/identity/claims/role
در
claim
ثبت شده است و این موضوع باعث میگردد.

        public bool CanUserAccess(ClaimsPrincipal user, string area, string controller, string action)
        {
            var currentClaimValue = $"{area}:{controller}:{action}";
            var securedControllerActions = _mvcActionsDiscoveryService.GetAllSecuredControllerActionsWithPolicy(ConstantPolicies.DynamicPermission);
            if (!securedControllerActions.SelectMany(x => x.MvcActions).Any(x => x.ActionId == currentClaimValue))
            {
                throw new KeyNotFoundException($@"The `secured` area={area}/controller={controller}/action={action} with `ConstantPolicies.DynamicPermission` policy not found. Please check you have entered the area/controller/action names correctly and also it's decorated with the correct security policy.");
            }

            if (!user.Identity.IsAuthenticated)
            {
                return false;
            }

            if (user.IsInRole(ConstantRoles.Admin))
            {
                // Admin users have access to all of the pages.
                return true;
            }

            // Check for dynamic permissions
            // A user gets its permissions claims from the `ApplicationClaimsPrincipalFactory` class automatically and it includes the role claims too.
            return user.HasClaim(claim => claim.Type == ConstantPolicies.DynamicPermissionClaimType &&
                                          claim.Value == currentClaimValue);
        }

User.IsInRole
همیشه
False
بر میگرداند.

در صورتی که در این زمینه راهنمایی بفرمایید ممنون می شوم.

Upgrading to .NET Core 2.0

I followed your steps for upgrading my project to .NET Core 2.0, the process was straightforward, thank you. now when I want to login to my website an exception will be thrown, here's the stack trace for the exception.

As you can see, it's because this line of code (ApplicationClaimsPrincipalFactory.cs), I have no idea why but it seems that it can't create Claim Principle for logged in user:

var principal = await base.CreateAsync(user).ConfigureAwait(false);

Here are my csproj file for each project:
MyProject.Core:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
    <AssemblyName>MyProject.Core</AssemblyName>
    <PackageId>MyProject.Core</PackageId>
    <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
    <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
    <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
  </PropertyGroup>
  <ItemGroup>
    <ProjectReference Include="../MyProject.Domain/MyProject.Domain.csproj" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="LinqKit.Microsoft.EntityFrameworkCore" Version="1.1.10" />
    <PackageReference Include="Microsoft.AspNetCore.Identity" Version="2.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="2.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="2.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="2.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="2.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Razor" Version="2.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.ViewFeatures" Version="2.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.0" PrivateAssets="All" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" PrivateAssets="All" />
    <PackageReference Include="Automapper" Version="5.1.1" />
    <PackageReference Include="iTextSharp.LGPLv2.Core" Version="1.2.3" />
    <PackageReference Include="MailKit" Version="1.10.1" />
    <PackageReference Include="CsvHelper" Version="2.16.3" />
    <PackageReference Include="ImageSharp" Version="1.0.0-alpha9-00112" />
    <PackageReference Include="System.ValueTuple" Version="4.3.1" />
  </ItemGroup>
  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
  </ItemGroup>
  <ItemGroup>
    <Reference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore">
      <HintPath>..\..\..\..\..\..\..\..\..\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.identity.entityframeworkcore\2.0.0\lib\netstandard2.0\Microsoft.AspNetCore.Identity.EntityFrameworkCore.dll</HintPath>
    </Reference>
  </ItemGroup>
</Project>

MyProject.Domain:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
    <DebugType>portable</DebugType>
    <AssemblyName>MyProject.Domain</AssemblyName>
    <PackageId>MyProject.Domain</PackageId>
    <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
    <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
    <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Identity.Stores" Version="2.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.0" />
    <PackageReference Include="Newtonsoft.Json" Version="10.0.3" />
    <PackageReference Include="System.ComponentModel.Annotations" Version="4.4.0" />
    <PackageReference Include="System.ValueTuple" Version="4.3.1" />
  </ItemGroup>
  <ItemGroup>
    <Compile Update="Models\BaseModel.cs">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Compile>
  </ItemGroup>
</Project>

MyProject.Web:

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
    <PreserveCompilationContext>true</PreserveCompilationContext>
    <AssemblyName>MyProject.Web</AssemblyName>
    <OutputType>Exe</OutputType>
    <PackageId>MyProject.Web</PackageId>
  </PropertyGroup>
  <ItemGroup>
    <ProjectReference Include="../MyProject.Domain/MyProject.Domain.csproj" />
    <ProjectReference Include="../MyProject.Core/MyProject.Core.csproj" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
    <PackageReference Include="Automapper" Version="5.1.1" />
    <PackageReference Include="iTextSharp.LGPLv2.Core" Version="1.2.3" />
    <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="5.1.4" />
    <PackageReference Include="System.ValueTuple" Version="4.4.0" />
  </ItemGroup>
  <Target Name="PrepublishScript" BeforeTargets="PrepareForPublish">
    <Exec Command="npm install" />
    <Exec Command="bower install" />
  </Target>
  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
  </ItemGroup>
  <ItemGroup>
    <Content Update="appsettings.json" CopyToPublishDirectory="Never" />
  </ItemGroup>
</Project>

Also here's my Startup.cs file:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<AppDbContext>();
    var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));
    services.Configure<JwtIssuerOptions>(options =>
    {
        options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
        options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
        options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
    });
    services.AddAuthentication().AddJwtBearer(cfg =>
    {
        cfg.TokenValidationParameters = new TokenValidationParameters()
        {
            ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],
            ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = _signingKey,
            ValidateLifetime = true
        };
    });
    services.AddMvc();
    services.AddScoped<ISecurityStampValidator, CustomSecurityStampValidator>();
    services.AddScoped<SecurityStampValidator<User>, CustomSecurityStampValidator>();
    services.AddScoped<SignInManager<User>, ApplicationSignInManager>();
    services.AddScoped<ApplicationUserManager, ApplicationUserManager>();
    services.AddScoped<UserManager<User>, ApplicationUserManager>();
    services.AddScoped<IUserClaimsPrincipalFactory<User>, ApplicationClaimsPrincipalFactory>();
    services.AddScoped<UserClaimsPrincipalFactory<User, IdentityRole>, ApplicationClaimsPrincipalFactory>();
    services.Configure<IdentityOptions>(options =>
    {
    });
    services.ConfigureApplicationCookie(identityOptionsCookies => {
        var provider = services.BuildServiceProvider();
        identityOptionsCookies.AccessDeniedPath = new PathString("/Account/Login");
    });
    services.AddIdentity<User, IdentityRole>(options =>
    {
        options.Password.RequireDigit = false;
        options.Password.RequireLowercase = false;
        options.Password.RequireUppercase = false;
        options.Password.RequireNonAlphanumeric = false;
        options.Password.RequiredLength = 3;

    }).AddEntityFrameworkStores<AppDbContext>()
        .AddDefaultTokenProviders();
    services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
    var serviceProvider = services.BuildServiceProvider();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseAuthentication();
    // other middleware: UseDeveloperExceptionPage, app.UseStaticFiles(); app.UseSession(); app.UseMvc....
}

Did I miss something?

netcore2.1 یا netstandard2.1

سلام، شما برای خود پروژه وب از نوع دات نت کر 2.1 استفاده می کنید و برای کلاس لایبرری ها از نت استاندارد؟
ممکنه در این مورد توضیح بدید که چرا این کار رو می کنید؟
چرا از دانت کر برای کلاس لایبرری ها استفاده نمی کنید؟

افزایش زمان اجرای درخواست در آپلود فایل

با سلام پروژه رو روی iis منتشر کردم برای آپلود فایل تنظیم زیر رو انجام دادم و محدودیت حجم آپلود رو نامحدود گذاشتم

public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<IISServerOptions>(options =>
            {
                options.MaxRequestBodySize = null;
            });

            services.AddControllersWithViews();
        }

و توی وب کانفیگ تنظیم زیر رو گذاشتم

<security>
    <requestFiltering>
      <!-- This will handle requests up to 300MB -->
      <requestLimits maxAllowedContentLength="314572800" />
    </requestFiltering>
  </security>

و توی تگ aspNetCore تو فایل وب کانفیگ هم حالت هاستینگ رو inprocess تنظیم هستش چطوری requestTimeout رو باید بیشتر از 2 دقیقه کنم

کد فایل وب کنفیگ که توی asp.net mvc استفاده میشد هم اینجا عمل نمیکنه

توی تگ aspNetCore وب کانفیگ خصوصیت requestTimeout هست که اونم کار نکرد

.NET Core SDK version: 3.1
IDE: 

امکان ثبت نام با شماره تلفن و یا نام کاربری

سلام و عرض ادب
امکان ثبت نام با شماره تلفن و یا نام کاربری رو میخواستم اضافه کنم
این بخش رو اضافه کردم اما باز عدم اجاره شماره رو میده
identityOptionsUser.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

اجرا نشدن پابلیش

Summary of the issue

آخرین نسخه رو بدون تغییر بصورت
X64
پابلیش میگیرم رو هاست اجرا نمیشه
حتی خوایتم رو کنسول با دستور
dotnet
اجرا کنم بازم اجرا نشد
خطایی هم نشون نمیده

Environment

.NET Core SDK version: 
IDE: 

Example code/Steps to reproduce:

paste your core code

Output:

Exception message:
Full Stack trace:

CreateAsync inside CustomUserClaimsPrincipalFactory doesn't get called

I'm going to store some additional claims into the database, I followed your blog post (part 4) But I couldn't get it to work. Here's step I followed:

  • Created my own implementation of IUserClaimsPrincipalFactory<TUser>:
public class ApplicationClaimsPrincipalFactory : UserClaimsPrincipalFactory<User, IdentityRole>
{
	public static readonly string ClubId = nameof(ClubId);

	public ApplicationClaimsPrincipalFactory(
	UserManager<User> userManager,
	RoleManager<IdentityRole> roleManager,
	IOptions<IdentityOptions> optionsAccessor) : base(userManager, roleManager, optionsAccessor)
	{
	}

	public override async Task<ClaimsPrincipal> CreateAsync(User user)
	{
		var principal = await base.CreateAsync(user); // adds all `Options.ClaimsIdentity.RoleClaimType -> Role Claims` automatically + `Options.ClaimsIdentity.UserIdClaimType -> userId` & `Options.ClaimsIdentity.UserNameClaimType -> userName`
		addCustomClaims(user, principal);
		return principal;
	}

	private static void addCustomClaims(User user, IPrincipal principal)
	{
		((ClaimsIdentity)principal.Identity).AddClaims(new[]
		{
			new Claim(ClaimTypes.NameIdentifier, user.Id.ToString(), ClaimValueTypes.Integer),
			new Claim(ClaimTypes.GivenName, user.FirstName ?? string.Empty),
			new Claim(ClaimTypes.Surname, user.LastName ?? string.Empty),
			// adding clubId to the claim
			new Claim(ClubId, user.ClubId.ToString(), ClaimValueTypes.String),
		});
	}
}
  • Registered the custom factory (I added this registration after services.AddIdentity() call):
services.AddScoped<IUserClaimsPrincipalFactory<User>, ApplicationClaimsPrincipalFactory>();
services.AddScoped<UserClaimsPrincipalFactory<User, IdentityRole>, ApplicationClaimsPrincipalFactory>();

But when I seed my database with this code:

var userAddResult = Task.Run(() => _userManager.CreateAsync(new User
{
	FirstName = x.FirstName,
	LastName = x.LastName,
	Email = x.Email,
	UserName = x.Username,
	Avatar = x.Avatar
}, x.Password)).Result;

CreateAsync method inside the custom factory doesn't get called.

PS: I also commented AddEntityFrameworkStores I also have this step in my application.

Is there other additional step that I must add in order to have this functionality?

Thanks 👍

Keeping track of online users

Thanks for sharing the project. well-done 👍 👍

In my application I want to keep track of online users. Based on the project what I have found so far:

  • Adding appropriate field (LastVisitDateTime)
  • Customizing SecurityStampValidator<User>
  • Customizing SignInManager<User>
  • Registering appropriate services:
services.AddScoped<ISecurityStampValidator, CustomSecurityStampValidator>();
services.AddScoped<SecurityStampValidator<User>, CustomSecurityStampValidator>();

services.AddScoped<IApplicationSignInManager, ApplicationSignInManager>();
services.AddScoped<SignInManager<User>, ApplicationSignInManager>();

I just followed this process, but after log-in, the browser redirects me to a blank page, Here's my identity setup:

services.AddIdentity<User, IdentityRole>()
                .AddEntityFrameworkStores<AppDbContext>()
                .AddDefaultTokenProviders();

services.AddScoped<ISecurityStampValidator, CustomSecurityStampValidator>();
services.AddScoped<SecurityStampValidator<User>, CustomSecurityStampValidator>();

services.AddScoped<IApplicationSignInManager, ApplicationSignInManager>();
services.AddScoped<SignInManager<User>, ApplicationSignInManager>();

services.Configure<IdentityOptions>(options =>
{
       //options.Password.RequiredLength = 8;
       //options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);                   
       //options.User.RequireUniqueEmail = true;
          options.Cookies.ApplicationCookie.AccessDeniedPath = new PathString("/Account/Login");
});

Is there something else to to?

خطا در هاست اشتراکی

من با پروژه فوق چندین سیستم توسعه داده ام
و به تازگی ورژن 3.1.1 دا دانلود کردم و پروژه جدیدی بر روی آن توسعه دادم
که پروژه در لوکال بخوبی کار میکند اما بر رو هاست اشتراکی خطا میدهد که با فعال کردن لاگ از وب کانفیگ خطای زیر را میگیرم
قابل ذکر است حتی پروژه خام را هم که پابلیش میگیرم و در هاست قرار میدهم همین خطا رو میگیرم

Unhandled exception. System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: ASPNETCoreIdentitySample.Services.Contracts.Identity.IEmailSender Lifetime: Scoped ImplementationType: ASPNETCoreIdentitySample.Services.Identity.AuthMessageSender': Unable to resolve service for type 'DNTCommon.Web.Core.IWebMailService' while attempting to activate 'ASPNETCoreIdentitySample.Services.Identity.AuthMessageSender'.) (Error while validating the service descriptor 'ServiceType: ASPNETCoreIdentitySample.Services.Contracts.Identity.ISmsSender Lifetime: Scoped ImplementationType: ASPNETCoreIdentitySample.Services.Identity.AuthMessageSender': Unable to resolve service for type 'DNTCommon.Web.Core.IWebMailService' while attempting to activate 'ASPNETCoreIdentitySample.Services.Identity.AuthMessageSender'.) (Error while validating the service descriptor 'ServiceType: ASPNETCoreIdentitySample.Services.Contracts.Identity.ISecurityTrimmingService Lifetime: Scoped ImplementationType: ASPNETCoreIdentitySample.Services.Identity.SecurityTrimmingService': Unable to resolve service for type 'DNTCommon.Web.Core.IMvcActionsDiscoveryService' while attempting to activate 'ASPNETCoreIdentitySample.Services.Identity.SecurityTrimmingService'.) (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Authorization.IAuthorizationHandler Lifetime: Scoped ImplementationType: ASPNETCoreIdentitySample.Services.Identity.DynamicPermissionsAuthorizationHandler': Unable to resolve service for type 'DNTCommon.Web.Core.IMvcActionsDiscoveryService' while attempting to activate 'ASPNETCoreIdentitySample.Services.Identity.SecurityTrimmingService'.) (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Authorization.IAuthorizationService Lifetime: Transient ImplementationType: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService': Unable to resolve service for type 'DNTCommon.Web.Core.IMvcActionsDiscoveryService' while attempting to activate 'ASPNETCoreIdentitySample.Services.Identity.SecurityTrimmingService'.) (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Authorization.IAuthorizationHandlerProvider Lifetime: Transient ImplementationType: Microsoft.AspNetCore.Authorization.DefaultAuthorizationHandlerProvider': Unable to resolve service for type 'DNTCommon.Web.Core.IMvcActionsDiscoveryService' while attempting to activate 'ASPNETCoreIdentitySample.Services.Identity.SecurityTrimmingService'.) (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Authorization.Policy.IPolicyEvaluator Lifetime: Transient ImplementationType: Microsoft.AspNetCore.Authorization.Policy.PolicyEvaluator': Unable to resolve service for type 'DNTCommon.Web.Core.IMvcActionsDiscoveryService' while attempting to activate 'ASPNETCoreIdentitySample.Services.Identity.SecurityTrimmingService'.)

تغییر رمز عبور توسط مدیر سایت

سلام به چه صورت میشه رمز بور کاربران توسط مدیرسایت تغییر کنه؟

در MVC من از این روش استفاده کردم و جواب میداد

var userModel = await _users.FirstOrDefaultAsync(row => row.Code == changePasswordViewModel.Code);
var applicationUserStoreService = new ApplicationUserStoreService(_unitOfWork.GetContext());
await applicationUserStoreService.SetPasswordHashAsync(userModel, PasswordHasher.HashPassword(changePasswordViewModel.Password));
await applicationUserStoreService.UpdateAsync(userModel);

Jwt

سلام
تلاش کردم دو پروژه DNTIdentity و ASPNETCore2JwtAuthentication را با هم ترکیب کنم
نیاز پروژه به این صورت هست که هم کلاینت های موبایلی داشته باشه و هم وب
مشکلات زیادی پیش اومده
مثلا برای کاربران سمت وب در یک area جدید، قسمت حذف که به صورت مودال و ایجکسی هست اررور 500 میده ولی بقیه قسمت ها که submit میشوند درست کار میکنند!
نیاز دارم اگر امکانش را دارید راهنمایی بفرمایید که مراحل اضافه کردن درست jwt به پروژه به چه صورت و ترتیبی هست تا مشکلات سیستم را برطرف کنم

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.