使用授权属性和身份服务器4保护ASP.NET Core Web API

时间:2018-11-20 19:53:14

标签: c# asp.net asp.net-web-api identityserver4

我设法使用their templates中的is4aspid设置了Identity Server 4,它似乎工作正常。现在,我正在尝试使用Asp.net Core 2.0保护Web Api。 Authorize似乎可以正常工作,但是当我尝试在控制器方法中使用[Authorize(Roles ="Admin")]时,它将无法正常工作。

我看着this video并试图做他们所做的事情,但是我找不到他们使用的大量代码,例如AuthorizationProviderClientapp.UseAuthorizationProvider()

这是我的Identity Server的Startup.cs ConfigureServices方法:

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

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

        services.AddMvc();

        services.Configure<IISOptions>(iis =>
        {
            iis.AuthenticationDisplayName = "Windows";
            iis.AutomaticAuthentication = false;
        });

        var builder = services.AddIdentityServer(options =>
        {
            options.Events.RaiseErrorEvents = true;
            options.Events.RaiseInformationEvents = true;
            options.Events.RaiseFailureEvents = true;
            options.Events.RaiseSuccessEvents = true;
        })
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApis())
            .AddInMemoryClients(Config.GetClients())
            .AddAspNetIdentity<ApplicationUser>();

        if (Environment.IsDevelopment())
        {
            builder.AddDeveloperSigningCredential();
        }
        else
        {
            throw new Exception("need to configure key material");
        }

        services.AddAuthentication()
            .AddGoogle(options =>
            {
                options.ClientId = "xxxx-xxxx.apps.googleusercontent.com";
                options.ClientSecret = "xxxxx";
            });
    }

这是配置类:

public static class Config
{
    public static IEnumerable<IdentityResource> GetIdentityResources()
    {
        return new IdentityResource[]
        {
            new IdentityResources.OpenId(),
            new IdentityResources.Profile()
        };
    }

    public static IEnumerable<ApiResource> GetApis()
    {
        return new ApiResource[]
        {
            //new ApiResource("api1", "My API #1") 
            new ApiResource("api1", "My API #1") { UserClaims = { "role" }  }
        };
    }

    public static IEnumerable<Client> GetClients()
    {
        return new[]
        {
            // https://www.scottbrady91.com/Angular/SPA-Authentiction-using-OpenID-Connect-Angular-CLI-and-oidc-client
            new Client {
                ClientId = "angular_spa",
                ClientName = "Intranet Web App",
                AllowedGrantTypes = GrantTypes.Implicit,
                AllowedScopes = new List<string> { "openid", "profile", "api1" },
                RedirectUris = new List<string> { "http://localhost:4200/auth-callback", "http://localhost:4200/silent-refresh.html" },
                PostLogoutRedirectUris = new List<string> { "http://localhost:4200/" },
                AllowedCorsOrigins = new List<string> { "http://localhost:4200" },
                AllowAccessTokensViaBrowser = true
            }
        };
    }
}

这是我的WebApi的Startup.cs ConfigureServices:

        public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvcCore()
            .AddAuthorization()
            .AddJsonFormatters();

        services.AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority = "http://localhost:5000";
                options.RequireHttpsMetadata = false;

                options.ApiName = "api1";
                options.EnableCaching = false;
                options.RoleClaimType = System.Security.Claims.ClaimTypes.Role;
            });
    }

然后配置:

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }           

        app.UseAuthentication();
        app.UseMvc();
    }

这是数据库中角色的方式: enter image description here

我从他们的样本中得到了这个API。当我使用邮递员发送Bearer令牌时,Authorize属性可以正常工作,现在我希望角色也能正常工作。我是否缺少nuget包或其他东西?

在此先感谢您的帮助

0 个答案:

没有答案