如何在IdentityServer4上的TestController上启用[授权]以用于声明CRUD控制器

时间:2017-02-18 18:09:15

标签: identityserver4

使用here中的OIDC客户端。 来自herehere的演示服务器。

我在IdentityServer上有以下控制器:

[Route("api/Test")]
//[Authorize]
[Authorize(ActiveAuthenticationSchemes = "Bearer")]
public class TestController : ControllerBase
{
    public IActionResult Get()
    {
        var claims = User.Claims.Select(c => new { c.Type, c.Value });
        return new JsonResult(claims);
    }
}

如果我注释掉两个[Authorize]属性,我会到达TestController。

如果我只使用[Authorize],则会收到以下错误:

  

GET http://localhost:5000/api/Test仪表板:1 XMLHttpRequest不能   加载http://localhost:5000/api/Test。没有'Access-Control-Allow-Origin'   标头出现在请求的资源上。起源   因此,“http://localhost:4200”不允许访问。响应   有HTTP状态代码500。

如果我只使用[Authorize(ActiveAuthenticationSchemes = "Bearer")],我会得到:

  

GET http://localhost:5000/api/Test仪表板:1 XMLHttpRequest不能   加载http://localhost:5000/api/Test。没有'Access-Control-Allow-Origin'   标头出现在请求的资源上。起源   因此,“http://localhost:4200”不允许访问。响应   有HTTP状态码500.仪表板:1 XMLHttpRequest无法加载   http://localhost:5000/api/Test。重定向   'http://localhost:5000/api/Test'来   'http://localhost:5000/Account/Login?ReturnUrl=%2Fapi%2FTest'已经过了   被CORS政策阻止:请求需要预检,即   不允许遵循跨源重定向。

我用来从OIDC客户端调用端点的代码是:

  test() {
   this.authService.mgr.getUser()
     .then(user => {
      //  this.http.get('https://api.identityserver.io/identity', 
      this.http.get('http://localhost:5000/api/Test', 
       { headers: new Headers({ 'Authorization': `${user.token_type} ${user.access_token}`}) })
         .subscribe(res => {
           console.log(res.json());
         });
     });
 }

我可以用此成功致电https://api.identityserver.io/identity

这是我的CorsPolicyHelper:

public class DemoCorsPolicy : ICorsPolicyService
{
    public Task<bool> IsOriginAllowedAsync(string origin)
    {
        return Task.FromResult(true);
    }
}

这就是它所谓的表单Startup:

 public void ConfigureServices(IServiceCollection services)
        {
...
            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<AuthDbContext>()
                .AddDefaultTokenProviders();

            services.AddMvc();
...
            services.AddIdentityServer()
                .AddTemporarySigningCredential()
                .AddInMemoryPersistedGrants()
                .AddInMemoryIdentityResources(Resources.GetIdentityResources())
                .AddInMemoryApiResources(Resources.GetApiResources())
                .AddInMemoryClients(Clients.GetClients())
                .AddAspNetIdentity<ApplicationUser>();

            services.AddTransient<ICorsPolicyService, DemoCorsPolicy>();
        }

最终目标是对权限/声明执行CRUD操作。我目前仍然坚持使用授权保护控制器这个看似微不足道的任务:/

1 个答案:

答案 0 :(得分:0)

最终,因为我能够在IdentityServer4之外成功使用[Authorize],所以我决定将授权与身份验证分开,并创建一个授权服务器,用于分离关注点。