4

を禁じられました。私はaugular-oauth2でangular 1.xを使用しています。数日後、私のエラーがAsp.netコアトークンベースのクレーム認証:ベアラは、私はOpenIdConnectServerでAsp.netコアRC2を使用してい

Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:54275/api/Account/Username 
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerMiddleware:Information: Successfully validated the token. 
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerMiddleware:Information: HttpContext.User merged via AutomaticAuthentication from authenticationScheme: Bearer. 
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerMiddleware:Information: AuthenticationScheme: Bearer was successfully authenticated. 
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Information: Authorization failed for user: . 
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Warning: Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'. 
Microsoft.AspNetCore.Mvc.ChallengeResult:Information: Executing ChallengeResult with authentication schemes (Bearer). 
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerMiddleware:Information: AuthenticationScheme: Bearer was forbidden. 

マイConfigureServicesにdigressedた私のconfigureが

app.UseWhen(context => context.Request.Path.StartsWithSegments(new PathString("/api")), branch => 
      { 
       branch.UseJwtBearerAuthentication(new JwtBearerOptions 
       { 
        AutomaticAuthenticate = true, 
        AutomaticChallenge = true, 
        RequireHttpsMetadata = false, 

        Audience = "http://localhost:54275/", 
        Authority = "http://localhost:54275/", 
        TokenValidationParameters = new TokenValidationParameters 
        { 
         ValidAudience = "client1", 
         //ValidAudiences = new List<string> { "", "empty", "null"} 
        } 
       }); 
      }); 

      app.UseOpenIdConnectServer(options => 
      { 
       options.AuthenticationScheme = OpenIdConnectServerDefaults.AuthenticationScheme; 
       options.Provider = new SimpleAuthorizationServerProvider(); 
       options.AccessTokenHandler = new JwtSecurityTokenHandler(); 
       options.ApplicationCanDisplayErrors = true; 
       options.AllowInsecureHttp = true; 
       options.TokenEndpointPath = new PathString("/oauth2/token"); 
       options.LogoutEndpointPath = new PathString("/oauth2/logout"); 
       options.RevocationEndpointPath = new PathString("/oauth2/revoke"); 
       options.UseJwtTokens(); 
       //options.AccessTokenLifetime = TimeSpan.FromHours(1); 
      }); 

私にauthorize属性が

とコントローラで定義されてい

services.AddAuthorization(options => 
      { 
       options.AddPolicy("UsersOnly", policy => 
       { 
        policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme); 
        policy.RequireClaim("role"); 
       }); 
      }); 

で構成されてい

[Authorize(Policy = "UsersOnly", ActiveAuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme), Route("api/Account")] 

私はトークンをクッキーとして保存し、httpインターセプターを使って要求にアタッチします。

私はこの問題に最後の3日間を過ごしてきたと私は、この時点で、私はおそらく睡眠不足に何かを明らかに欠けていることを実感

public override async Task GrantResourceOwnerCredentials(GrantResourceOwnerCredentialsContext context) 
     { 
      // validate user credentials (demo mode) 
      // should be stored securely (salted, hashed, iterated) 
      using (var con = new SqlConnection(ConnectionManager.GetDefaultConnectionString())) 
      { 
       if (!Hashing.ValidatePassword(context.Password, await con.ExecuteScalarAsync<string>("SELECT PassHash FROM dbo.Users WHERE Username = @UserName", new { context.UserName }))) 
       { 
        context.Reject(
         error: "bad_userpass", 
         description: "UserName/Password combination was invalid." 
         ); 
        return; 
       } 

       // create identity 
       var id = new ClaimsIdentity(context.Options.AuthenticationScheme); 
       id.AddClaim(new Claim("sub", context.UserName)); 
       id.AddClaim(new Claim("role", "user")); 

       // create metadata to pass on to refresh token provider 
       var props = new AuthenticationProperties(new Dictionary<string, string> 
       { 
        {"as:client_id", context.ClientId} 
       }); 
       var ticket = new AuthenticationTicket(new ClaimsPrincipal(id), props, 
        context.Options.AuthenticationScheme); 
       ticket.SetAudiences("client1"); 
       //ticket.SetScopes(OpenIdConnectConstants.Scopes.OpenId, OpenIdConnectConstants.Scopes.Email, OpenIdConnectConstants.Scopes.Profile, "api-resource-controller"); 
       context.Validate(ticket); 
      } 
     } 

でトークンを生成します。どんな助けもありがとう。

+0

は、拡張メソッドが含まれていますUseOpenIdConnectServer – schmidlop

答えて

4

あなたが見ているエラーは、おそらく2つの要因によって引き起こされる:

  • それはアクセストークンでシリアル化されることはありませんので、あなたは、あなたのカスタムrole請求への明示的な送信先を添付していません。このセキュリティ機能の詳細については、on this other SO postを参照してください。ここでは、roleはおそらくhttp://schemas.microsoft.com/ws/2008/06/identity/claims/roleClaimTypes.Role)に置き換えられます:IdentityModelは、よく知られたJWTが自分ClaimTypes同等に主張して変換する内部マッピングを使用して

  • policy.RequireClaim("role");は、OTBが動作しない場合があります。代わりにpolicy.RequireRole("user")を使用することをおすすめします。

また、それはすでにOpenIDのConnectサーバーミドルウェアによって自動的に行われますように手動client_idを格納する必要がないことは注目に値します。

あなたは承認さプレゼンター(ここでは、クライアント識別子)のリストを返しますticket.GetPresenters()を使用して、それを取得することができます。クライアントAに発行されたリフレッシュトークンをクライアントBが使用できないように自動的に保証するので、独自のコードでこのチェックを行う必要はありません。コアアセンブリをDOTNET

関連する問題