ASP.NET Core 2.0:用户授权失败:(null)

时间:2018-03-16 11:11:11

标签: c# .net-core asp.net-core-2.0 identityserver4

我正在构建一个Web API和IdentityServer4位于同一.Net Core 2.0项目中的应用程序。此API由Aurelia SPA网络应用程序使用。 IdentityServer4设置为使用JWT和ImplicitFlow。一切正常(客户端应用程序被重定向到登录,获取令牌,将其发送回标头等)直到用户需要在API控制器中获得授权,然后它无法授权用户,因为它是空的。

存在许多类似的问题,但我尝试了所有提出的解决方案,但没有一个能为我工作。我已经在这个问题上花了2天时间,开始失去希望和耐心。我可能错过了一些明显的东西,但却找不到它。我在这里发布我的配置 - 它们有什么问题?将不胜感激任何帮助。

My Startup课程(我省略了一些额外的东西,比如日志,本地化等):

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.AddCors(options =>
        {
            options.AddPolicy("default", policy =>
            {
                policy.WithOrigins(Config.APP1_URL)
                    .AllowAnyHeader()
                    .AllowAnyMethod();
            });
        });

        services.AddMvc();

        services.Configure<IdentityOptions>(options =>
        {
            // Password settings
            options.Password.RequireDigit = false;
            options.Password.RequiredLength = 8;
            options.Password.RequireNonAlphanumeric = false;
            options.Password.RequireUppercase = false;
            options.Password.RequireLowercase = false;
            options.Password.RequiredUniqueChars = 4;

            // Lockout settings
            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
            options.Lockout.MaxFailedAccessAttempts = 10;
            options.Lockout.AllowedForNewUsers = true;

            // User settings
            options.User.RequireUniqueEmail = true;
        });

        services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryPersistedGrants()
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients())
            .AddAspNetIdentity<ApplicationUser>();

        services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority = Config.HOST_URL + "/";
                options.RequireHttpsMetadata = false;
                options.ApiName = "api1";
            });
    }

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

        app.UseStaticFiles();

        app.UseIdentityServer();

        app.UseAuthentication();

        app.UseCors("default");

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

这是我的Config类:

public class Config
{
    public static string HOST_URL = "http://dev.example.com:5000";
    public static string APP1_URL = "http://dev.example.com:9000";

    public static IEnumerable<IdentityResource> GetIdentityResources()
    {
        return new List<IdentityResource>
        {
            new IdentityResources.OpenId(),
            new IdentityResources.Profile()
        };
    }

    public static IEnumerable<ApiResource> GetApiResources()
    {
        return new List<ApiResource>
        {
            new ApiResource("api1", "My API")
        };
    }

    public static IEnumerable<Client> GetClients()
    {
        return new List<Client>
        {
            new Client
            {
                ClientId = "reporter",
                ClientName = "ReporterApp Client",
                AccessTokenType = AccessTokenType.Jwt,
                AllowedGrantTypes = GrantTypes.Implicit,
                RequireConsent = false,
                AllowAccessTokensViaBrowser = true,
                RedirectUris =
                {
                    $"{APP1_URL}/signin-oidc"
                },
                PostLogoutRedirectUris = {
                    $"{APP1_URL}/signout-oidc"
                },
                AllowedCorsOrigins = {
                    APP1_URL
                },

                AllowedScopes =
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    "api1"
                }
            }
        };
    }
}

令牌Aurelia应用程序来自IdentityServer:

{
    "alg": "RS256",
    "kid": "52155e28d23ddbab6154ce0c34511c9a",
    "typ": "JWT"
},
{
    "nbf": 1521195164,
    "exp": 1521198764,
    "iss": "http://dev.example.com:5000",
    "aud": ["http://dev.example.com:5000/resources", "api1"],
    "client_id": "reporter",
    "sub": "767381df-446a-4c34-af27-7bdf9e4563f3",
    "auth_time": 1521195163,
    "idp": "local",
    "scope": ["openid", "profile", "api1"],
    "amr": ["pwd"]
}

2 个答案:

答案 0 :(得分:1)

首先交换您的订单UseAuthencation会写一些东西。

app.UseAuthentication();
app.UseIdentityServer();

第二次更改cookie方案。 Identityserver4有自己的,因此您的用户为空,因为它没有读取cookie。

services.AddAuthentication(IdentityServerConstants.DefaultCookieAuthenticationScheme)
                .AddIdentityServerAuthentication(options =>
                {
                    // base-address of your identityserver
                    options.Authority = Configuration.GetSection("Settings").GetValue<string>("Authority");
                    // name of the API resource
                    options.ApiName = "testapi";
                    options.RequireHttpsMetadata = false;
                }); 

第三个想法:

我必须将类型添加到api调用,以便它将读取持有者令牌。

[HttpPost("changefiscal")]
[Authorize(AuthenticationSchemes = "Bearer")]
public async Task<ActionResult> ChangeFiscal([FromBody] long fiscalId)
  {
   // STuff here
   }

答案 1 :(得分:0)

嗯,现在终于可以了。 我找到了答案here

所有必要的做法是在Startup类(services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme))中替换“Bearer”身份验证方案,如下所示:

services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })

编辑:当我有一个有效的令牌时,它工作了一会儿。可能授权仍然有效,但现在我有另一个问题 - 身份验证被破坏,登录页面进入循环。太复杂了。

编辑2。找到工作解决方案here

有必要添加两个

services.AddMvc(config =>
            {
                var defaultPolicy = new AuthorizationPolicyBuilder(new[] { IdentityServerAuthenticationDefaults.AuthenticationScheme, IdentityConstants.ApplicationScheme })
                    .RequireAuthenticatedUser()
                    .Build();
                config.Filters.Add(new AuthorizeFilter(defaultPolicy));
            })

和默认身份验证方案

services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)

进入Startup类