首頁  >  文章  >  後端開發  >  IdentityServer4 授權配置AllowedScopes實例

IdentityServer4 授權配置AllowedScopes實例

零下一度
零下一度原創
2017-06-24 10:48:343415瀏覽

1. 業務場景

IdentityServer4 授權配置Client中的AllowedScopes,設定的是特定的API 網站名字,也就是使用方設定的ApiName,範例程式碼:

//授权中心配置new Client
{
    ClientId = "client_id_1",
    AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
    AllowOfflineAccess = true,
    AccessTokenLifetime = 3600 * 6, //6小时SlidingRefreshTokenLifetime = 1296000, //15天ClientSecrets =
    {new Secret("secret".Sha256())
    },
    AllowedScopes = 
    {"api_name1"},
}//API 服务配置app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
    Authority = $"http://localhost:5000",
    ApiName = "api_name1",
    RequireHttpsMetadata = false});

上面兩個api_name1設定一致,問題來了,因為授權中心的scope配置是整個API 服務,如果我們有多個Client配置,例如一個前台和後台,然後都需要存取api_name1,就會出現一些問題。

例如,api_name1服務中的一個介面服務設定碼:

[Authorize()]
[Route("api/values")]
[HttpGet]public IActionResult Get()
{return Ok();
}

Authorize()的配置,說明api/values介面需要授權後訪問,如果授權中心配置了兩個Client(前台和後台),並且scope都包含了api_name1 ,現在就會出現兩種情況:

  1. 前台Client和後台Client,都需要授權後存取 api/values介面:沒有問題。

  2. 前台Client不需要授權後訪問,後台Client需要授權後訪問:有問題,前台Client沒辦法訪問了,因為api/values介面設定了Authorize()

其實,說明白些,就是該如何讓 API 服務指定Client授權存取?例如:[Authorize(ClientId = 'client_id_1')]

2. 解決方案

沒有[Authorize(ClientId = 'client_id_1')]這種解決方式,不過可以使用[Authorize(Roles = ' admin')]

授權中心的ResourceOwnerPasswordValidator程式碼,修改如下:

public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
{private readonly IUserService _userService;public ResourceOwnerPasswordValidator(IUserService userService)
    {
        _userService = userService;
    }public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
    {var user = await _userService.Login(context.UserName, context.Password);if (user != null)
        {var claims = new List<Claim>() { new Claim("role", "admin") }; //根据 user 对象,设置不同的 rolecontext.Result = new GrantValidationResult(user.UserId.ToString(), OidcConstants.AuthenticationMethods.Password, claims);
        }
    }
}

授權中心的startup配置,修改如下

var builder = services.AddIdentityServer();
builder.AddTemporarySigningCredential()//.AddInMemoryIdentityResources(Config.GetIdentityResources()).AddInMemoryApiResources(new List<ApiResource>
        {new ApiResource("api_name1", "api1"){ UserClaims = new List<string> {"role"}}, //增加 role claimnew ApiResource("api_name2", "api2"){ UserClaims = new List<string> {"role"}}
        })
        .AddInMemoryClients(Config.GetClients());

API 服務接口,只需要配置如下:

[Authorize()]
[Route("api/values")]
[HttpGet]public IActionResult Get()
{return Ok();
}

[Authorize(Roles = "admin")]
[Route("api/values2")]
[HttpGet]public IActionResult Get2()
{return Ok();
}

[Authorize(Roles = "admin,normal")]
[Route("api/values3")]
[HttpGet]public IActionResult Get3()
{return Ok();
}

需要注意的是,api/values介面雖然沒有設定具體的Roles,但每個Role都可以存取。

以上是IdentityServer4 授權配置AllowedScopes實例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn