2016-10-05 11 views
0

IdentityServer4 및 다른 클라이언트 ASP.NET 핵심 응용 프로그램을 설치했습니다. 클라이언트는 IdentityServer로 인증하고 표준 MVC 웹 API 프로젝트 인 세 번째 응용 프로그램에 대한 액세스를 요청해야합니다.IdentityServer, ASP.NET 코어 및 웹 API

내가 클라이언트 자격 증명을 달성하기위한 단계를 따라했습니다

https://identityserver.github.io/Documentation/docsv2/overview/simplestOAuth.html

지금은 완전히 처음 무기명 토큰을 인식하고 나에게 접근하는 몇 가지 권한 부여를 제공하기 위해 웹 API를 활용하는 방법에 분실하고이 예에서 흐름 웹 API 끝점.

내 IdentityServer Statrup.cs

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

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

    public IConfigurationRoot Configuration { get; } 

    // This method gets called by the runtime. Use this method to add services to the container 
    public void ConfigureServices(IServiceCollection services) 
    { 
     services.AddIdentityServer() 
       .AddInMemoryStores() 
       .AddInMemoryClients(Config.GetClients()) 
       .AddInMemoryScopes(Config.GetScopes());   
    } 

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline 
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
    { 
     loggerFactory.AddConsole(LogLevel.Debug); 
     app.UseDeveloperExceptionPage(); 

     app.UseIdentityServer(); 
    } 
} 

과 Config.cs입니다

ASP.NET 코어가 IdentityServer 및 웹 API 호출
public class Config 
{ 
    // scopes define the resources in your system 
    public static IEnumerable<Scope> GetScopes() 
    { 
     return new List<Scope> 
     { 
      new Scope 
      { 
       Name = "api1" 
      } 
     }; 
    } 

    // clients want to access resources (aka scopes) 
    public static IEnumerable<Client> GetClients() 
    { 
     // client credentials client 
     return new List<Client> 
     { 
      // no human involved 
     new Client 
     { 
      ClientName = "Silicon-only Client", 
      ClientId = "silicon", 
      Enabled = true, 
      AccessTokenType = AccessTokenType.Reference, 

      AllowedGrantTypes = GrantTypes.ClientCredentials, 

      ClientSecrets = new List<Secret> 
      { 
       new Secret("F621F470-9731-4A25-80EF-67A6F7C5F4B8".Sha256()) 
      }, 

      AllowedScopes = new List<string> 
      { 
       "api1" 
      } 
     } 
     }; 
    }} 

[Route("api/testing")] 
    public class TestingController : Controller 
    { 
     // GET: api/values 

     [HttpGet] 
     public IActionResult Get() 
     { 
      var responce = GetClientToken(); 

      return Json(new 
      { 
       message = CallApi(responce) 
      }); 
     } 

     static TokenResponse GetClientToken() 
     { 
      var client = new TokenClient(
       Constants.TokenEndpoint, 
       "silicon", 
       "F621F470-9731-4A25-80EF-67A6F7C5F4B8"); 

      return client.RequestClientCredentialsAsync("api1").Result; 
     } 

     static string CallApi(TokenResponse response) 
     { 
      var client = new HttpClient 
      { 
       BaseAddress = new Uri(Constants.AspNetWebApiSampleApi), 
       Timeout = TimeSpan.FromSeconds(10) 
      }; 
      client.SetBearerToken(response.AccessToken); 
      try 
      {     
       var auth = client.GetStringAsync().Result; 
       return auth; 
      } 
      catch (Exception ex) 
      { 
       return ex.Message; 

      } 
     } 
    } 

그래서 수 누구나 설명하거나 공유 할 수있는 몇 가지 링크를 공유하는 웹 APi (owin 미들웨어와 함께) 통화를 처리 할 ASP.NET 코어 클라이언트에서? Owin Configuration (IAppBuilder 앱) 메서드에 어떤 설정을 적용해야합니까?

답변

1

우선 MVC 클라이언트에 동의 화면을 표시하려면 ScopeType.Resource를 추가해야하는 리소스가 API에서 처리되므로 API 범위에 의 ScopeType을 추가해야합니다. 당신은 또한 당신이 당신의 API를 말해 그게 때문에 OwinStartup 클래스를 추가 할 필요가 당신의 API 프로젝트에서

new Scope 
{ 
    Name = "api", 
    DisplayName = "Your scopes display name", 
    Type = ScopeType.Resource, 
    Claims = new List<ScopeClaim> 
    { 
     new ScopeClaim("role") 
    } 
} 

: 표시 이름을 추가하고 당신이 당신의 API에 추가 주장을해야하는 경우, 주장의 목록에 추가 무기명 토큰 인증을 사용하십시오 : 시작 구성에서 :

app.UseIdentityServerBearerTokenAuthentication(
    new IdentityServerBearerTokenAuthenticationOptions 
    { 
     Authority = "YourIdentityServersAddress.com/identity", 
     RequiredScopes = new[] { "api" }, 
    }); 
app.UseWebApi(WebApiConfig.Register()); 

마지막 줄은 webapi-config를 등록하기위한 것입니다. 당신이 지정한 기관 (즉, 귀하의 Identity-Server 및 IdentityServers Startup-File에 지정한 범위)을 지정하는 곳입니다. 당신은 또한 당신의 API의 시작에 "... UseIdentityServerBearer"당신이 전에 다음 줄을 추가 할 필요가 특정 역할에 대한 권한을 부여하기위한 사용자 정의 AuthorizationManager (예를 추가하려면 :

app.UseResourceAuthorization(new AuthorizationManager()); 

을 AuthorizationManager은 어디 ResourceAuthorizationManager 클래스에서 상속하여 직접 구현 한 클래스입니다. 그러나 이것에 대해 자세히 알고 싶지는 않습니다. 자세한 내용은 여기를 참조하십시오.

그리고 귀하의 API 컨트롤러에 추가하면됩니다 [Authorize] 속성 위의 방법을 사용하면 전체 컨트롤러가 승인 받아야하는 경우 클래스 수준에서 또는 클래스 수준에서 액세스 권한을 부여하지 않아도됩니다. 당신은 예를 들어 역할 인증을 사용하려면 (당신이 필요로하는 것 [ResourceAuthorize].

을 다른 문의 사항이 있거나

+0

감사를 물어 주시기 알고 싶은 경우에, 마지막으로 내가 어디에서 조금 이동 붙어있는 – zdrsh