【问题标题】:ASP.NET Core 2.0: Authorization failed for user: (null)ASP.NET Core 2.0:用户授权失败:(null)
【发布时间】:2018-08-25 10:33:10
【问题描述】:

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

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

我的 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?}");
        });
    }
}

这是我的配置类:

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"]
}

【问题讨论】:

  • 不知道为什么人们不赞成这些事情。赞成撤消那个废话。

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


【解决方案1】:

首先交换您的订单 UseAuthencation over writes 一些东西。

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

第二次更改 cookie 方案。 Identityserver4 有自己的,因此您的用户为 null,因为它没有读取 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
   }

【讨论】:

  • 感谢您的回复。不幸的是,它没有帮助。另外,关于饼干。我没有在我的请求中发送任何 cookie,我在授权标头中发送了一个不记名令牌,cookie 方案如何参与其中?将感谢链接到一些解释它的文章。
  • 我实际上是在我的 Identityserver 中执行此操作的,其中有一个 api 端点。我记得它让我疯狂地试图让它工作,诀窍是弄清楚我做了什么来让它工作。我刚刚添加了另一个想法,尝试添加 AuthenticationSchemes。我真的应该为此写一篇文章,我花了几天时间才让它工作
  • 我实际上刚刚在这里的另一个问题中找到了解决方案,关于 SO。将在几秒钟内发布答案。谢谢你的帮助,它实际上把我送到了正确的方向。
【解决方案2】:

嗯,现在终于可以使用了。 我找到了答案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)

进入启动类

【讨论】:

  • 尝试在重定向 URL 的末尾添加一个“/”。
  • 如果您不想这样做,请在 Global.asax 中添加一个 Session_Start() 方法。 (这两个 cmets 与你的无限重定向有关)
  • 不幸的是,重定向 URL 末尾的“/”会导致“Invalid redirect_uri”错误。
  • 哦,它必须在客户端启动和 IdentityServer 端的配置上匹配。如果我没记错的话,您要么需要 Session_Start() 方法,要么需要重定向末尾的“/”。即使你要去同一个地方,它也会对配置进行字符串匹配。
  • 如果我能帮到你,请查看我最近的问题。我现在对 cookie 过期以及如何设置它完全迷失了。 :)
猜你喜欢
  • 2018-01-30
  • 2018-03-12
  • 2018-04-03
  • 2018-09-29
  • 2018-06-02
  • 2018-05-20
  • 2021-06-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多