2015-10-28 4 views
5

Visual Studio 2015 EnterpriseおよびASP.NET vNext Beta8を使用して、JWTトークンを発行し、消費するエンドポイントを構築しています。私は当初、hereのように自分自身でトークンを生成してこれにアプローチしました。 後で@Pinpointによって役に立つarticleが、トークンを発行して消費するようにAspNet.Security.OpenIdConnect.Server(a.k.a. OIDC)を構成できることが明らかになりました。AspNet.Security.OpenIdConnect.Server(ASP.NET vNext)によって発行されたトークンの妥当性確認

だから私は、これらの指示に従ったエンドポイントを立ち上がって、そしてpostmanからx-www-form-urlencodedでポストを提出することによって、私は合法的なトークンをバック受け取る:

{ 
    "token_type": "bearer", 
    "access_token": "eyJ0eXAiO....", 
    "expires_in": "3599" 
} 

これは素晴らしいですが、またどこ動けなくなる。ここでコントローラの動作に注釈を付けて、このベアラトークンを要求する方法を教えてください。

私は私がしなければならないだろうすべては、 [承認(「ベアラー」)]と私のコントローラメソッドを飾る認証方式を追加していると思った:

 services.AddAuthorization 
     (
      options => 
      { 
       options.AddPolicy 
       (
        JwtBearerDefaults.AuthenticationScheme, 
        builder => 
        { 
         builder. 
         AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme). 
         RequireAuthenticatedUser(). 
         Build(); 
        } 
       ); 
      } 
     ); 

そして "と私のコントローラのアクションを呼び出しますAuthorization bearer eyJ0eXAiO .... "というヘッダーを使用していました。悲しいことに、このすべてのアプローチは、例外を生成するものの、やっているようです:

要求の処理中に未処理の例外が発生しました。リモートサーバに

HttpRequestExceptionを接続することができません:

のSocketExceptionを:ターゲットマシンが積極的127.0.0.1:50000

WebException拒否したため、接続できませんでした要求を送信中にエラーが発生しました。

IOException:IDX10804: 'http://localhost:50000/.well-known/openid-configuration'からドキュメントを取得できません。 Microsoft.IdentityModel.Logging.LogHelper.Throw(文字列メッセージ、タイプexceptionType、EventLevel LOGLEVEL、例外のInnerException)

例外InvalidOperationException:IDX10803: 'http://localhost:50000/.well-known/openid-configuration':から設定を取得できません。内部例外: 'IDX10804:' http://localhost:50000/.well-known/openid-configuration 'からドキュメントを取得できません。'


再現する(しかし、この生産価値のあるコードを考慮しないでください)、次のステップを考えてみましょう:

  • を説明here

  • オープンとしてASP.NETベータ8のツールを適用しますVisual Studio Enterprise 2015を開き、新しいWeb APIを作成するASP.NET 5プレビューテンプレートプロジェクト

  • 変更project.json

    {
    "ウェブルート": "wwwrootの"、
    "バージョン": "1.0.0- *"、

    "依存性":{
    「Microsoft.AspNet。IISPlatformHandler ":" 1.0.0-beta8 "、
    " Microsoft.AspNet.Mvc ":" 6.0.0-beta8 "、
    " Microsoft.AspNet.Server.Kestrel ":" 1.0.0-beta8 "、
    "Microsoft.AspNet.Authentication.JwtBearer": "1.0.0-ベータ8"、
    "AspNet.Security.OpenIdConnect.Server": "1.0.0-ベータ3"、
    "Microsoft.AspNet.Authentication.OpenIdConnect" "1.0.0-ベータ8"、
    "Microsoft.Framework.ConfigurationModel.Json": "1.0.0-beta4"、
    "Microsoft.AspNet.Diagnostics": "1.0.0-ベータ8"
    }

    "コマンド":{
    "ウェブ": "Microsoft.AspNet.Server.Kestrel"
    }、

    "フレームワーク":{
    "dnx451":{}
    }、

    "除外":[
    "wwwrootの"、
    "node_modules"
    ]、
    "publishExclude":[
    ".user"、
    "
    .vs PSCC」
    ]
    }

  • 変更Startup.cs(これはピンポイントの元の記事@の礼儀で次のように。 I)は、コメントを削除し、AddAuthorizationのスニップを追加しました:

public class Startup 
{ 
    public Startup(IHostingEnvironment env) 
    { 
    } 

    public void ConfigureServices(IServiceCollection services) 
    { 
     services.AddAuthorization 
     (
      options => 
      { 
       options.AddPolicy 
       (
        JwtBearerDefaults.AuthenticationScheme, 
        builder => 
        { 
         builder. 
         AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme). 
         RequireAuthenticatedUser(). 
         Build(); 
        } 
       ); 
      } 
     ); 
     services.AddAuthentication(); 
     services.AddCaching(); 
     services.AddMvc(); 
     services.AddOptions(); 
    } 

    // Configure is called after ConfigureServices is called. 
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, IOptions<AppSettings> appSettings) 
    { 
     app.UseDeveloperExceptionPage(); 

     // Add a new middleware validating access tokens issued by the OIDC server. 
     app.UseJwtBearerAuthentication(options => { 
      options.AutomaticAuthentication = true; 
      options.Audience = "http://localhost:50000/"; 
      options.Authority = "http://localhost:50000/"; 
      options.ConfigurationManager = new ConfigurationManager<OpenIdConnectConfiguration> 
      (
       metadataAddress : options.Authority + ".well-known/openid-configuration", 
       configRetriever : new OpenIdConnectConfigurationRetriever(), 
       docRetriever : new HttpDocumentRetriever { RequireHttps = false } 
      ); 
     }); 

     // Add a new middleware issuing tokens. 
     app.UseOpenIdConnectServer 
     (
      configuration => 
      { 
       configuration.Options.TokenEndpointPath= "/authorization/v1"; 
       configuration.Options.AllowInsecureHttp = true; 
       configuration.Provider = new OpenIdConnectServerProvider { 

        OnValidateClientAuthentication = context => 
        { 
         context.Skipped(); 
         return Task.FromResult<object>(null); 
        }, 

        OnGrantResourceOwnerCredentials = context => 
        { 
         var identity = new ClaimsIdentity(OpenIdConnectDefaults.AuthenticationScheme); 
         identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "todo") ); 
         identity.AddClaim(new Claim("urn:customclaim", "value", "token id_token")); 
         context.Validated(new ClaimsPrincipal(identity)); 
         return Task.FromResult<object>(null); 
        } 
       }; 
      } 
     ); 

     app.UseMvc(); 
    } 
} 
  • 変更が承認属性を指定するValuesController.csをwizarded:
[Route("api/[controller]")] 
public class ValuesController : Controller 
{ 
    // GET: api/values 
    [Authorize("Bearer")] 
    [HttpGet] 
    public IEnumerable<string> Get() 
    { 
     return new string[] { "value1", "value2" }; 
    } 
} 
  • は、プロジェクトを実行し、 postmanを使用してトークンを取得します。 「パスワード」の「grant_type」とトークンの使用x-www-form-urlencodedでPOST、「ユーザ名」何でも、「パスワード」何と「資源」APIエンドポイントのアドレスを取得するには。たとえば、私の特定のURLはhttp://localhost:37734/authorization/v1です。

  • コピーBase64でエンコードされたトークンは、その後postmanを用いwizarded値コントローラを呼び出すためにトークンを使用します。トークンを使用するには、ヘッダーContent-Type application/jsonとAuthorization bearer eyJ0eXAiO ....(自分のトークン)を使ってGETを行います。私の特定のURLはhttp://localhost:37734/api/valuesです。

  • は、前述の例外を確認します。

私は上記しようとしている[承認(「ベアラー」)]のアプローチは、誰かが私が使ってJWTトークンを摂取する方法についてのベストプラクティスを理解するのに役立つことができれば、私は非常に感謝だろう行くには間違った方法であればOIDC。

ありがとうございます。

+0

注: 'options.TokenValidationParameters.ValidateAudience'を削除して、トークンリクエストを行うときに' resource'パラメータを使用することを検討してください。これは、将来のバージョンで必須になる可能性があるためです。あなたのフォームデータ(JS側)に単に '&resource = http%3A%2F%2Flocalhost%3A37734%2F'を追加すればうまくいくはずです。私はそれを言及する私の元の記事を更新しました。 – Pinpoint

+0

@Pinpoint、ありがとう。トークンをリクエストするときにリソースリクエストを追加し、トークンを受け取るようにしました。{ "sub": "todo"、 "iss": "http:// localhost:37734 /"、 "aud": " "http:// localhost:37734 /"、 "exp":1446131180、 "nbf":1446127580 } options.TokenValidationParameters.ValidateAudience = falseをコメントアウトし、受け取ったトークンを使用しようとすると "IDX10208:Unable to validationParameters.ValidAudienceがnullまたは空白で、validationParameters.ValidAudiencesがnullです。 – 42vogons

+0

'option.Audience =" http:// localhost:37734/";'をJWTベアラ認証オプションに追加することを忘れないでください) – Pinpoint

答えて

3

options.Authorityは(すなわち、あなたのOIDCサーバーのアドレス)発行者のアドレスに対応します。

http://localhost:50000/あなたの質問に後でhttp://localhost:37734/を使用しているため、正しいとは思われません。 URLを修正してもう一度試してみてください。

+0

ありがとうございました! – 42vogons

関連する問題