2017-02-18 12 views
2

Использование OIDC-клиента от here. И демонстрационный сервер от here и here.Как включить [Авторизовать] на TestController на IdentityServer4 с требованием CRUD-контроллер

У меня есть следующий контроллер на самом 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 dashboard:1 XMLHttpRequest cannot load http://localhost:5000/api/Test . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://localhost:4200 ' is therefore not allowed access. The response had HTTP status code 500.

А если я просто использовать [Authorize(ActiveAuthenticationSchemes = "Bearer")] я получаю:

GET http://localhost:5000/api/Test dashboard:1 XMLHttpRequest cannot load http://localhost:5000/api/Test . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://localhost:4200 ' is therefore not allowed access. The response had HTTP status code 500. dashboard:1 XMLHttpRequest cannot load http://localhost:5000/api/Test . Redirect from ' http://localhost:5000/api/Test ' to ' http://localhost:5000/Account/Login?ReturnUrl=%2Fapi%2FTest ' has been blocked by CORS policy: Request requires preflight, which is disallowed to follow cross-origin redirect.

Код, я использую для вызова конечной точки из РСИНА клиент:

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); 
    } 
} 

И это, где его называют формой запуска:

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 по разрешений/требований. Я в настоящее время застрял в этой, казалось бы, тривиальной задаче иметь защищенный от авторизации контроллер:/

ответ

0

В конечном счете, так как я успешно использовал [Authorize] за пределами IdentityServer4, я решил отделить авторизацию от аутентификации и создать сервер авторизации, который предусматривает разделение проблем.

 Смежные вопросы

  • Нет связанных вопросов^_^