2017-01-18 30 views
5

Asp.netコア用の既存のKeycloakクライアントはありますか? I have found a NuGet package for .netですが、Coreでは動作しません。このセキュリティサーバーと簡単に統合する方法(あるいは他の選択肢を使用する方法)はありますか?ASP.NETコアのKeycloakクライアント

+0

これに必要なリソースはありますか? – devqon

+0

KeyCloak(Authority:server + "auth/realms /" + realm、ClientId、ClientSecret)用にOpenIdConnectOptionsを埋め込んだMicrosoft.AspNetCore.Authentication.OpenIdConnectのUseOpenIdConnectAuthenticationを使用してみてください。 – mikes

+0

@mikes AspNetCoreとkeycloakで提案しているこの構成のオンラインサンプルを知っていますか?好奇心の外に、あなたは答えではなく、答えの中で以下の答えを提示してみませんか?その違いを思い出す... – Talisker

答えて

1

私たちのために働いていた事は(それのクッキーベースの認証)Startup.csにこれらの事を設定した

public void Configure(...) 
{ 
    (...) 
    app.UseCookieAuthentication(new CookieAuthenticationOptions 
    { 
     AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme, 
     AutomaticAuthenticate = true, 
     CookieHttpOnly = true, 
     CookieSecure = CookieSecurePolicy.SameAsRequest 
    }); 

    app.UseOpenIdConnectAuthentication(CreateOpenIdConnectOptions(_customConfig)); 
    (...) 
} 

とオプションを設定する:

private OpenIdConnectOptions CreateOpenIdConnectOptions(CustomConfigurationFile configuration) 
{ 
    var options = new OpenIdConnectOptions 
    { 
     AuthenticationScheme = "oidc", 
     SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme, 
     Authority = configuration.ServerAddress + "/auth/realms/" + configuration.Realm, 
     RequireHttpsMetadata = true, 
     PostLogoutRedirectUri = configuration.SystemAddress, 
     ClientId = configuration.ClientId, 
     ClientSecret = configuration.ClientSecret, 
     ResponseType = OpenIdConnectResponseType.Code, 
     GetClaimsFromUserInfoEndpoint = true, 
     SaveTokens = true 
    }; 
    options.Scope.Clear(); 
    options.Scope.Add("openid"); 
    return options; 
} 
+1

このソリューションでは、[Autorize(Roles = "MyKeycloakRole")]などの標準認可属性を使用できますか?言い換えると、KeyCloakで定義された役割は、OpenIdConnectAuthenticationによって自動的に抽出されますか?歓声 – Talisker

9

私がプレイしました今日これで少し。最も直接的な方法はOpenId標準もあまりにも使用しています。 Startup.csで

IはOpenIdConnect認証使用:

public void Configure(...) 
    { (...) 
     app.UseCookieAuthentication(new CookieAuthenticationOptions 
     { 
      AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme, 
      AutomaticAuthenticate = true, 
      CookieHttpOnly = true, 
      CookieSecure = CookieSecurePolicy.SameAsRequest 
     }); 
     app.UseOpenIdConnectAuthentication(CreateKeycloakOpenIdConnectOptions());`(...) 
}` 

OpenIdConnectOptions方法:appsettings.jsonにおいて

private OpenIdConnectOptions CreateKeycloakOpenIdConnectOptions() 
    { 
     var options = new OpenIdConnectOptions 
     { 
      AuthenticationScheme = "oidc", 
      SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme, 
      Authority = Configuration["Authentication:KeycloakAuthentication:ServerAddress"]+"/auth/realms/"+ Configuration["Authentication:KeycloakAuthentication:Realm"], 
      RequireHttpsMetadata = false, //only in development 
      PostLogoutRedirectUri = Configuration["Authentication:KeycloakAuthentication:PostLogoutRedirectUri"], 
      ClientId = Configuration["Authentication:KeycloakAuthentication:ClientId"], 
      ClientSecret = Configuration["Authentication:KeycloakAuthentication:ClientSecret"], 
      ResponseType = OpenIdConnectResponseType.Code, 
      GetClaimsFromUserInfoEndpoint = true, 
      SaveTokens = true 

     }; 
     options.Scope.Add("openid"); 
     return options; 
    } 

Keycloakための構成を追加:

{ 
 
    (...), 
 
    "Authentication": { 
 
    "KeycloakAuthentication": { 
 
     "ServerAddress": "http://localhost:8180", 
 
     "Realm": "demo", 
 
     "PostLogoutRedirectUri": "http://localhost:57630/", 
 
     "ClientId": "KeycloakASPNETCore", 
 
     "ClientSecret": "secret-get-it-in-keycloakConsole-client-credentials" 
 
    } 
 
    } 
 
}

Keycloakクライアントは、以下のようにconfiguerdさ:

私はこのような何かをロール別のユーザを許可したい場合

ConfigureServicesメソッドにauthorization by claimsを追加します。

public void ConfigureServices(IServiceCollection services) 
    { 
     (...) 

     services.AddAuthorization(options => 
     { 
      options.AddPolicy("Accounting", policy => 
      policy.RequireClaim("member_of", "[accounting]")); //this claim value is an array. Any suggestions how to extract just single role? This still works. 
     }); 
    } 

私はValuesController(既定のWeb APIテンプレート)でgetメソッドを編集した:

[Authorize(Policy = "Accounting")] 
[Route("api/[controller]")] 
public class ValuesController : Controller 
{ 
    // GET api/values   
    [HttpGet] 
    public Dictionary<string,string> Get() 
    { 
     var userPrinciple = User as ClaimsPrincipal; 
     var claims = new Dictionary<string, string>(); 

     foreach (var claim in userPrinciple.Claims) 
     { 
      var key = claim.Type; 
      var value = claim.Value; 

      claims.Add(key, value); 
     } 


     return claims; 
    } 

私は会計の役割を持っているか、会計の役割を持つグループであるユーザーでログインした場合、それが表示されるはずです私のユーザーは、アドレスlocalhost:57630/api/valuesに対する主張をしています。

私はこれがうまくいきたいと思います。

+0

非常に便利で完全な答え!私が働くことができない唯一のことは、マッパー 'member_of'です、それはユーザーの主張のリストには存在しません。作成に使用した設定を共有してもよろしいですか?ありがとう。 – Gimly

+1

'member_of'を作成するには、クライアントの[マッパー]タブの[作成]をクリックします。 'Mapper Type'は 'User Client Role'と 'Add to ID token'に設定する必要があります。ユーザーをログアウトすると、変更内容がユーザーの要求に表示されます。 – frogec

+1

@gimlyユーザーに複数のロールがある場合は、カスタム・ポリシー・ベースの認可を使用して各ユーザーのロールをチェックすることで認可できます。 – frogec

0

あなたはKeycloakクライアントの役割、そのような設定で標準の.NETの役割のマッピングを使用する場合:

Startup.cs:

services.AddAuthorization(options => 
    { 
     options.AddPolicy("Users", policy => 
     policy.RequireRole("Users")); 
    }); 

    services.AddAuthentication(options => 
    { 
     options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; 
     options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; 
     options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; 
    }) 
    .AddCookie() 
    .AddOpenIdConnect(options => 
    { 
     options.Authority = Configuration["Authentication:oidc:Authority"] 
     options.ClientId = Configuration["Authentication:oidc:ClientId"]; 
     options.ClientSecret = Configuration["Authentication:oidc:ClientSecret"]; 
     options.RequireHttpsMetadata = false; 
     options.GetClaimsFromUserInfoEndpoint = true; 
     options.SaveTokens = true; 
     options.RemoteSignOutPath = "/SignOut"; 
     options.SignedOutRedirectUri = "Redirect-here"; 
     options.ResponseType = "code"; 

    }); 

のAppSettings。JSON:

"Authentication": { 
    "oidc": { 
     "Authority":"http://your-keycloak-server/auth/realms/your-realm", 
     "ClientId":"Your-Client-Name", 
     "ClientSecret":"Your-client-secret" 
    } 
    } 

Keycloakクライアント設定:

  • が新しいトークンマッパー
  • Mapper-Values(独自のクライアント名を入力してください)

今、あなたは適用するために、標準のauthorize役割ステートメントを使用することができますを作成します。 ASP.NETプロジェクトへのKeycloakクライアントロール:

[Authorize(Roles = "Users")]