具有AspNetIdentity的IdentityServer4。如何获得对UserDb的WebApi访问权限

时间:2018-11-02 07:06:46

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

IdentityServer4上有一个已配置的授权服务。 具有webApi访问权限的数据库必须移到单独的项目中。

只有通过IdentityServer4的授权用户才能使用用户访问webApi。

  1. L代表IdentityServer4,这只是您需要提供访问权限的另一个api(作用域)。

  2. 要与用户合作,您需要使用AspNetIdentity来访问UserManager <ApplicationUser>RoleManager <ApplicationUser>服务

    如果我添加services.AddIdentity<ApplicationUser,IdentityRole>(),则通过IdentityServer4的授权将停止工作。 如果我未添加,则UserManager<ApplicationUser>RoleManager<ApplicationUser>服务将不可用。

为用户设置webApi

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

        services.AddIdentity<ApplicationUser, IdentityRole>()      // authorization with token (IdentityServer4) stops working
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();


        services.AddMvcCore()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddAuthorization(options =>
            {
                options.AddPolicy("AdminsOnly", policyUser =>
                {
                    policyUser.RequireClaim("role", "admin");
                });
                options.AddPolicy("ManagerOnly", policyUser =>
                {
                    policyUser.RequireClaim("role", "manager");
                });
            })
            .AddJsonFormatters();

        services.AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority = "http://localhost:5000"; 
                options.RequireHttpsMetadata = false;         
                options.ApiName = "UserDbApi";                
                options.EnableCaching = true;
                options.CacheDuration = TimeSpan.FromMinutes(10);
            });

        services.AddCors(options =>        
        {
            options.AddPolicy("default", policy =>
            {
                policy.WithOrigins("http://localhost:5003")       //access Js client
                    .AllowAnyHeader()
                    .AllowAnyMethod();
            });
        });
    }

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

        app.UseCors("default");
        app.UseAuthentication();
        app.UseHttpsRedirection();
        app.UseMvc();
    }

访问测试控制器

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    // GET api/values
    [HttpGet]
    [Authorize(Roles = "SuperAdmin")]
    public ActionResult<IEnumerable<string>> Get()
    {
      // Access works only with a token issued by IdentityServer4
    }
}

Js客户

var config = {
    authority: "http://localhost:5000",
    client_id: "js",
    redirect_uri: "http://localhost:5003/callback.html",
    response_type: "id_token token",
    scope: "openid profile custom.profile api1 UserDbApi",
    post_logout_redirect_uri: "http://localhost:5003/index.html",
    checkSessionInterval: 30000,
    revokeAccessTokenOnSignout: true,
    automaticSilentRenew: true,
    silent_redirect_uri: 'http://localhost:5003/callback-silent.html',
    accessTokenExpiringNotificationTime: 60
};
var mgr = new Oidc.UserManager(config);

function getInfo() {
    mgr.getUser().then(function (user) {
        var url = "https://localhost:7000/api/values";

        var xhr = new XMLHttpRequest();
        xhr.open("GET", url);
        xhr.onload = function () {
            log(xhr.status, JSON.parse(xhr.responseText));
        }
        xhr.setRequestHeader("Authorization", "Bearer " + user.access_token);
        xhr.send();
    });
}

AspNetIdentity提供的授权使我受阻!

请帮助!

0 个答案:

没有答案