2016-10-05 18 views
0

IdentityServer4と別のクライアントASP.NETコアアプリケーションをセットアップしました。 クライアントはIdentityServerで認証し、標準のMVC Web APIプロジェクトである第3のアプリケーションへのアクセスを要求する必要があります。IdentityServer、ASP.NETコアおよびWeb API

私はクライアントの資格情報は、最初のベアラトークンを認識して、私にアクセスするためのいくつかの許可を与えることをWEB APIを取得する方法に今、私は完全に失われています。この例から https://identityserver.github.io/Documentation/docsv2/overview/simplestOAuth.html

フロー達成するための手順に従ってきましたWeb 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

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

ASP.NETコアはIdentityServerとWeb API

[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; 

      } 
     } 
    } 

に呼び出すことができますので、誰でも私のWEB APi(owinミドルウェア)を使って呼び出しを処理するにはどうすればいいですかASP.NET Coreクライアントから? Owin Configuration(IAppBuilder app)メソッドにどのような設定を入れるべきですか?

答えて

1

まず、api-scopeに というScopeTypeを追加する必要があります。あなたのMVC-Clientに同意画面を表示するには、ScopeType.Resourceを追加する必要があるリソースが必要です。あなたはまた、あなたがあなたのAPIを教えてthatsのため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を登録することだけです。 あなたのAuthorityを指定する場所、つまり、あなたのIdentity-Serverと、IdentityServers Startup-Fileで指定したスコープを指定します。 また、あなたはAPIのスタートアップで「UseIdentityServerBearer ...」の前に次の行を追加する必要があり、特定の役割のために承認するためのカスタム認可マネージャ・(例えばを追加したい場合は、次の

app.UseResourceAuthorization(new AuthorizationManager()); 

認可マネージャ・である場合クラスから継承して自分で実装するクラスResourceAuthorizationManagerしかし、私は深く掘り下げたいとは思っていません(これについてさらに質問があれば、私はもっと深く幸せになるでしょう)

あなたのAPIのコントローラでは、追加する必要があります。[Authorize]属性メソッドの上に、あなたのコントローラ全体が許可されなければならない場合、クラスレベルで、またはクラスレベルでのアクセスを許可することができません。 (あなたが例えば、役割の認証を使用する場合は、[ResourceAuthorize]が必要になります。

さらにご質問があるか

+0

おかげで気軽にお知りになりたい場合は、最終的に私はあった場所から少し移動立ち往生 – zdrsh

関連する問題