【问题标题】:The controllers with [Authorize] attribute return unauthorized error but the ones with [Authorize(Roles = "Administrator")] work perfectly具有 [Authorize] 属性的控制器返回未经授权的错误,但具有 [Authorize(Roles = "Administrator")] 的控制器完美运行
【发布时间】:2018-02-14 14:49:21
【问题描述】:

使用以下登录方法和“Startup.cs”,具有 [Authorize(Roles = "Administrator")] 属性的控制器工作正常,但需要经过身份验证的用户且不关心其角色的控制器返回“状态代码:401 未授权”。

登录方式:

    public async void LogOn(IUser user, string domain, bool remember, TimeSpan timeout)
    {
        var context = AccessorsHelper.HttpContextAccessor.HttpContext;

        await context.SignOutAsync(IdentityConstants.ApplicationScheme);

        var claims = new List<Claim>
        {
            new Claim(ClaimsIdentity.DefaultNameClaimType, user.GetId().ToString())
        };

        claims.AddRange(user.GetRoles().Select(role => new Claim(ClaimsIdentity.DefaultRoleClaimType, role)));

        await context.SignInAsync(IdentityConstants.ApplicationScheme,
            new ClaimsPrincipal(new ClaimsIdentity(claims)),
            new AuthenticationProperties
            {
                IsPersistent = remember,
                ExpiresUtc = DateTimeOffset.UtcNow.Add(timeout)
            });
    }

Startup.cs:

public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.InjectOliveDependencies();

        var builder = services.AddMvc(options => {
            options.ModelBinderProviders.Insert(0, new Olive.Mvc.OliveBinderProvider());
            //options.ModelBinderProviders.Insert(0, new TestBinderProvider());
        })
        .ConfigureApplicationPartManager(manager =>
        {
            var oldMetadataReferenceFeatureProvider = manager.FeatureProviders.First(f => f is MetadataReferenceFeatureProvider);
            manager.FeatureProviders.Remove(oldMetadataReferenceFeatureProvider);
            manager.FeatureProviders.Add(new ReferencesMetadataReferenceFeatureProvider());
        }); ;
        //ConfigureMvc(builder);

        services.Configure<RazorViewEngineOptions>(options => {
            options.ViewLocationExpanders.Add(new ViewLocationExpander());
        });

        services.AddSingleton<IUserStore<User>, UserStore>();
        services.AddSingleton<IRoleStore<string>, RoleStore>();
        services.AddIdentity<User, string>();
        services.AddAuthentication(IdentityConstants.ApplicationScheme);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.ConfigureOliveDependencies(env);

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseAuthentication();

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            //routes.MapRoute(
            //    name: "default",
            //    template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

另外,我使用的是 ASP.Net Core 2.0。

【问题讨论】:

  • LogOn 方法真的需要[Authorize] 属性吗?它应该允许匿名访问每个尝试登录的人...
  • @BalagurunathanMarimuthu 我的LogOn 方法没有[Authotize] 属性。我只是提供方法,因为我认为它应该有问题。

标签: c# authentication asp.net-core authorization asp.net-core-mvc


【解决方案1】:

LogIn 方法稍作改动,问题就解决了。

    public async void LogOn(IUser user, string domain, bool remember, TimeSpan timeout)
    {
        var context = AccessorsHelper.HttpContextAccessor.HttpContext;

        await context.SignOutAsync(IdentityConstants.ApplicationScheme);

        var claims = new List<Claim>
        {
            new Claim(ClaimsIdentity.DefaultNameClaimType, user.GetId().ToString())
        };

        claims.AddRange(user.GetRoles().Select(role => new Claim(ClaimsIdentity.DefaultRoleClaimType, role)));

        await context.SignInAsync(IdentityConstants.ApplicationScheme,
            new ClaimsPrincipal(new ClaimsIdentity(claims, "AuthenticationType")), // AuthenticationType is just a text and I do not know what is its usage.
            new AuthenticationProperties
            {
                IsPersistent = remember,
                ExpiresUtc = DateTimeOffset.UtcNow.Add(timeout)
            });
    }

检查注释部分是否有更改。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-14
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-17
    相关资源
    最近更新 更多