使用IdentityServer的MVC客户端中的ASP.NET身份导致循环

时间:2019-03-02 10:18:41

标签: asp.net-core asp.net-identity identityserver4

我有一个使用IdentityServer进行身份验证的Asp.NET Core应用程序。
这很好。
现在,我想在我的应用程序中使用ASP.NET Core Identity来管理角色,声明等。

文档说我应该为此添加service.AddIdentity ...
但是,当我在客户端中将其添加到Startup.cs时,使用IdentityServer的登录将不再起作用。

我将被重定向到IdentityServer,登录并重定向回客户端(这很好)
但是,然后我的客户端抛出有关授权的错误,然后再次重定向到IdentityServer。这会导致无限循环

Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 POST http://localhost:44331/signin-oidc application/x-www-form-urlencoded 5297
Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler:Information: AuthenticationScheme: Cookies signed in.
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 184.9938ms 302 
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:44331/  
Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler:Information: Identity.Application was not authenticated. Failure message: Unprotect ticket failed
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Route matched with {action = "Index", controller = "Home", page = "", area = ""}. Executing action TestApplication.Controllers.HomeController.Index (TestApplication)
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Information: Authorization failed.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
Microsoft.AspNetCore.Mvc.ChallengeResult:Information: Executing ChallengeResult with authentication schemes ().
Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler:Information: AuthenticationScheme: oidc was challenged.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action TestApplication.Controllers.HomeController.Index (TestApplication) in 15.4912ms
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 29.286ms 302 
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 POST http://localhost:44331/signin-oidc application/x-www-form-urlencoded 5297
-- and it starts all over again

有人知道我在做什么错吗?

这是我的Startup.cs

public class Startup
{
    public Startup(IConfiguration configuration, IHostingEnvironment environment)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(environment.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{environment.EnvironmentName}.json", optional: true);

        builder.AddEnvironmentVariables();
        Configuration = builder.Build();            
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        services.AddTransient<ApiService>();
        services.AddSingleton(Configuration);
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

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

        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => false;
            options.MinimumSameSitePolicy = SameSiteMode.None;                       
        });


        services.AddAuthentication(options =>
        {
            options.DefaultScheme = "Cookies";
            options.DefaultChallengeScheme = "oidc";
        })
        .AddCookie()
        .AddOpenIdConnect("oidc", options =>
        {
            options.SignInScheme = 'Cookies';
            options.UseTokenLifetime = true; 

            options.Authority = 'https://localhost:44350; 
            options.RequireHttpsMetadata = true;

            options.ClientId = Configuration.GetValue<string>("IdentityServer:ClientId");
            options.ClientSecret = Configuration.GetValue<string>("IdentityServer:ClientSecret");
            options.ResponseType = "code id_token token"

            options.SaveTokens = true;
            options.GetClaimsFromUserInfoEndpoint = true;

            options.Scope.Add("api1");                
            options.Scope.Add("offline_access");
            options.Scope.Add("openid");
            options.Scope.Add("profile");
            options.Scope.Add("email");

            options.TokenValidationParameters.NameClaimType = "name";
            options.TokenValidationParameters.RoleClaimType = "role";

        });

        services.AddMvc(config =>
        {
            var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
            config.Filters.Add(new AuthorizeFilter(policy));
        });

        services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddJsonOptions(x => x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore)
            .AddJsonOptions(x => x.SerializerSettings.NullValueHandling = NullValueHandling.Ignore);
    }

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

        app.UseAuthentication();
        app.UseHttpsRedirection();
        app.UseCookiePolicy();


        app.UseMvc(routes =>
        {
            routes.MapRoute(
               name: "areas",
               template: "{area:exists}/{controller}/{action}/{id?}");

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

    }
}

2 个答案:

答案 0 :(得分:0)

在Identity Server方面,您可以创建Profile Service,以在发放令牌时使IDS4包括角色声明。然后在客户端,您可以将角色声明从JWT令牌映射到声明原则。您可以参考here中的代码示例。

要管理用户或角色,您可以在Identity Server4应用程序中提供API端点,或者创建新的应用程序作为另一个资源来管理数据库,您的客户端应用程序将从Identity Server 4获取访问令牌以访问您的新应用程序,通过将令牌附加到用于管理API调用的HTTP授权标头中来发送请求。

答案 1 :(得分:0)

如果还有其他人仍然想通过IdSrv进行身份验证但要管理IdSrv之外的用户,请替换此:

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

在您的客户端应用中与此

services.AddIdentityCore<IdentityUser>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    //.AddDefaultUI() // use standard identity UI forms for register, forgot pass etc.
    .AddDefaultTokenProviders();

取消注释上面的行以使用MS身份中的标准UI表单,但请注意,之后您必须覆盖默认的登录逻辑。这是通过将身份支架添加到您的项目中来完成的。