Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ASP.NET Core 2.0身份验证不起作用_C#_Asp.net_Asp.net Core_Asp.net Identity_Asp.net Core Identity - Fatal编程技术网

C# ASP.NET Core 2.0身份验证不起作用

C# ASP.NET Core 2.0身份验证不起作用,c#,asp.net,asp.net-core,asp.net-identity,asp.net-core-identity,C#,Asp.net,Asp.net Core,Asp.net Identity,Asp.net Core Identity,我正在尝试在我的ASP.NET Core 2.0项目中使用Identity实现身份验证,但它似乎不起作用。我将Identity实现到的最后一个项目是ASP.NETMVC5项目,情况发生了重大变化。我跳过了Core1.0和1.1,所以我不知道在这两个版本下是如何实现的,尽管从我所阅读的内容来看,应该是大致相似的 但是我不能让它为我工作。当我说它不工作时,我的意思是,即使我没有被授权,我也没有被重定向到登录页面 我所做的唯一定制就是实现我自己的用户存储和扩展来添加标识,而不需要角色,因为我不打算使用

我正在尝试在我的ASP.NET Core 2.0项目中使用Identity实现身份验证,但它似乎不起作用。我将Identity实现到的最后一个项目是ASP.NETMVC5项目,情况发生了重大变化。我跳过了Core1.0和1.1,所以我不知道在这两个版本下是如何实现的,尽管从我所阅读的内容来看,应该是大致相似的

但是我不能让它为我工作。当我说它不工作时,我的意思是,即使我没有被授权,我也没有被重定向到登录页面

我所做的唯一定制就是实现我自己的用户存储和扩展来添加标识,而不需要角色,因为我不打算使用角色。我可以用一些方向来解释我搞砸了什么,因为从我的角度来看,现在一切都太复杂了。以下是我目前掌握的代码:

Startup.cs

public void ConfigureServices(
    IServiceCollection services) {
    services.AddDbContext<CustomDbContext>();
    services.AddTransient<IUserStore<GlobalUser>, CustomUserStore<GlobalUser>>();
    services.AddIdentity<GlobalUser>();
    services.AddMvc();
}

public void Configure(
    IApplicationBuilder app,
    IHostingEnvironment env) {
    if (env.IsDevelopment()) {
        app.UseDeveloperExceptionPage();
    } else {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();
    app.UseAuthentication();
    app.UseMvc();
}
公共void配置服务(
IServiceCollection服务){
services.AddDbContext();
services.AddTransient();
服务。附加性();
services.AddMvc();
}
公共无效配置(
IApplicationBuilder应用程序,
IHostingEnvironment(环境){
if(env.IsDevelopment()){
app.UseDeveloperExceptionPage();
}否则{
app.UseExceptionHandler(“/Home/Error”);
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc();
}
ServiceCollectionExtensions.cs

public void ConfigureServices(
    IServiceCollection services) {
    services.AddDbContext<CustomDbContext>();
    services.AddTransient<IUserStore<GlobalUser>, CustomUserStore<GlobalUser>>();
    services.AddIdentity<GlobalUser>();
    services.AddMvc();
}

public void Configure(
    IApplicationBuilder app,
    IHostingEnvironment env) {
    if (env.IsDevelopment()) {
        app.UseDeveloperExceptionPage();
    } else {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();
    app.UseAuthentication();
    app.UseMvc();
}
我只是查看了内置的
AddIdentity
的源代码,省略了与角色相关的内容,所以这里不应该有问题,尽管可能

public static class ServiceCollectionExtensions {
    public static IdentityBuilder AddIdentity<TUser>(
        this IServiceCollection services,
        Action<IdentityOptions> optionsAction = null)
        where TUser : class {
        services.AddAuthentication(
            o => {
                o.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
                o.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
                o.DefaultSignInScheme = IdentityConstants.ApplicationScheme;
            }).AddCookie(
            o => {
                o.LoginPath = new PathString("/Login");
                o.Events = new CookieAuthenticationEvents {
                    OnValidatePrincipal = SecurityStampValidator.ValidatePrincipalAsync
                };
            });

        services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.TryAddScoped<IUserValidator<TUser>, UserValidator<TUser>>();
        services.TryAddScoped<IPasswordValidator<TUser>, PasswordValidator<TUser>>();
        services.TryAddScoped<IPasswordHasher<TUser>, PasswordHasher<TUser>>();
        services.TryAddScoped<ILookupNormalizer, UpperInvariantLookupNormalizer>();
        services.TryAddScoped<IdentityErrorDescriber>();
        services.TryAddScoped<ISecurityStampValidator, SecurityStampValidator<TUser>>();
        services.TryAddScoped<IUserClaimsPrincipalFactory<TUser>, UserClaimsPrincipalFactory<TUser>>();
        services.TryAddScoped<UserManager<TUser>, AspNetUserManager<TUser>>();
        services.TryAddScoped<SignInManager<TUser>, SignInManager<TUser>>();

        if (optionsAction != null) {
            services.Configure(optionsAction);
        }

        return new IdentityBuilder(typeof(TUser), services);
    }
}
公共静态类ServiceCollectionExtensions{
公共静态标识生成器附加标识(
这是电子收款服务,
操作选项操作=空)
图瑟:上课在哪里{
services.AddAuthentication(
o=>{
o、 DefaultAuthenticateScheme=IdentityConstants.ApplicationScheme;
o、 DefaultChallengeScheme=IdentityConstants.ApplicationScheme;
o、 DefaultSignInScheme=IdentityConstants.ApplicationScheme;
}).AddCookie(
o=>{
o、 LoginPath=新路径字符串(“/Login”);
o、 事件=新CookieAuthenticationEvents{
OnValidatePrincipal=SecurityStampValidator.ValidatePrincipalAsync
};
});
services.TryAddSingleton();
services.TryAddScoped();
services.TryAddScoped();
services.TryAddScoped();
services.TryAddScoped();
services.TryAddScoped();
services.TryAddScoped();
services.TryAddScoped();
services.TryAddScoped();
services.TryAddScoped();
如果(选项动作!=null){
服务。配置(选项操作);
}
返回新的IdentityBuilder(typeof(TUser),services);
}
}
我认为我必须像MVC5那样添加授权过滤器,但我似乎不能全局地这样做。将其应用于默认控制器时,会出现以下异常:

未指定authenticationScheme,并且没有 DefaultChallengeScheme已找到


但我以为我是在自定义
附加属性
方法中设置方案的?我需要一些指导,我很感激有人送我去。

我和你有同样的问题。我必须基于
FormsAuthentication
cookie实现自定义身份验证,这在.net core中不存在,我们有一些ASP.net系统使用
FormsAuthentication
,我们需要互操作。我解决这个问题的方法是将
AuthorizeFilter
子类化,然后
覆盖
OnAuthorizationAsync(AuthorizationFilterContext上下文)
。这就是我的想法:

public class AuthFilter : AuthorizeFilter
{

    public override Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
        if (context.Filters.Any(item => item is IAsyncAuthorizationFilter && item != this || item is IAllowAnonymousFilter))
        {
            return Task.FromResult(0);
        }

        if (!context.HttpContext.User.Identity.IsAuthenticated)
        {
            context.Result = new UnauthorizedResult();
            return Task.FromResult(0);
        }

        return base.OnAuthorizationAsync(context);
    }

}
然后您必须在
Startup.cs
中的
ConfigureServices
中注册它,即

services.AddMvc(options =>
{
    options.Filters.Add(new AuthFilter(
        new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build()));
});

这将是默认设置,使所有控制器都需要授权。如果您需要匿名登录,请将
[AllowAnonymous]
添加到您的控制器中

我遇到了与您相同的问题。我必须基于
FormsAuthentication
cookie实现自定义身份验证,这在.net core中不存在,我们有一些ASP.net系统使用
FormsAuthentication
,我们需要互操作。我解决这个问题的方法是将
AuthorizeFilter
子类化,然后
覆盖
OnAuthorizationAsync(AuthorizationFilterContext上下文)
。这就是我的想法:

public class AuthFilter : AuthorizeFilter
{

    public override Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
        if (context.Filters.Any(item => item is IAsyncAuthorizationFilter && item != this || item is IAllowAnonymousFilter))
        {
            return Task.FromResult(0);
        }

        if (!context.HttpContext.User.Identity.IsAuthenticated)
        {
            context.Result = new UnauthorizedResult();
            return Task.FromResult(0);
        }

        return base.OnAuthorizationAsync(context);
    }

}
然后您必须在
Startup.cs
中的
ConfigureServices
中注册它,即

services.AddMvc(options =>
{
    options.Filters.Add(new AuthFilter(
        new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build()));
});

这将是默认设置,使所有控制器都需要授权。如果您需要匿名登录,请将
[AllowAnonymous]
添加到您的控制器中

我发现了这一点,而我在制作自己的
附加属性
扩展时忽略了一些东西。在传入选项之前,我应该将
IdentityConstants.ApplicationScheme
作为参数传入
AddCookie
。我仔细检查了身份来源,发现我漏掉了。我一加上它,一切都好了。因此:

//           ▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼ this is what was missing
}).AddCookie(IdentityConstants.ApplicationScheme,
o => {

这最终是我自己造成的问题…

我想出来了,是我在制作自己的
附加功能时忽略了一些东西。在传入选项之前,我应该将
IdentityConstants.ApplicationScheme
作为参数传入
AddCookie
。我仔细检查了身份来源,发现我漏掉了。我一加上它,一切都好了。因此:

//           ▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼ this is what was missing
}).AddCookie(IdentityConstants.ApplicationScheme,
o => {

这最终是我自己造成的问题…

您是否将方案作为控制器中“授权”属性的一部分传入?像这样:
[Authorize(AuthenticationSchemes=IdentityConstants.ApplicationScheme)]
,或者类似的东西?我不知道
IdentityConstants.ApplicationScheme
是否是您需要的枚举。S