使用IdentityServer4,在一個ASPNetCore專案中,配置oidc和api的AccessToken兩種認證授權
阿新 • • 發佈:2018-12-14
1.配置兩種認證方式
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); services.AddAuthentication(options => { options.DefaultScheme = "Cookies"; options.DefaultChallengeScheme = "oidc"; }) .AddCookie("Cookies") .AddOpenIdConnect("oidc", options => { options.SignInScheme = "Cookies"; options.Authority = GZSetting.ApiAuthIp; options.RequireHttpsMetadata = false; options.ClientId = GZSetting.MvcClientId; options.ClientSecret= GZSetting.ClientSecret; options.ResponseType = "code id_token"; options.Scope.Clear(); options.Scope.Add("openid"); options.Scope.Add(GZSetting.ApiName); //options.Scope.Add("roles"); options.SaveTokens = true; options.GetClaimsFromUserInfoEndpoint = true; options.ClaimActions.MapUniqueJsonKey("role", "role"); }) .AddIdentityServerAuthentication("Bearer", options => { options.RequireHttpsMetadata = false; options.Authority = GZSetting.ApiAuthIp; options.ApiName = GZSetting.ApiName; });
2.配置授權策略
services.AddAuthorization(option => { //預設 只寫 [Authorize],表示使用oidc進行認證 option.DefaultPolicy = new AuthorizationPolicyBuilder("oidc").RequireAuthenticatedUser().Build(); //ApiController使用這個 [Authorize(Policy = "ApiPolicy")],使用jwt認證方案 option.AddPolicy("ApiPolicy", policy => { policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme); policy.RequireAuthenticatedUser(); }); });
3.給Webapi的控制器新增授權標籤
[Authorize(Policy = "ApiPolicy")] [Route("api/[controller]/[action]")] [ApiController] public class TestInfoController : ControllerBase