我正在尝试使用IdentityServer4实现"基于角色的授权",以基于用户角色访问我的API.
例如,我想为用户提供两个角色,即FreeUser和PaidUser,并希望通过授权属性使用[Authorize(Roles ="FreeUser"))]来访问API,请帮助我如何实现这一点.
我有以下解决方案结构:
我已经注册了我的Javascript客户端,如下所示:
new Client
{
ClientId = "js",
ClientName = "javascript client",
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser= true,
RedirectUris = {"http://localhost:5004/callback.html"},
PostLogoutRedirectUris = {"http://localhost:5004/index.html"},
AllowedCorsOrigins = {"http://localhost:5004"},
AllowedScopes =
{
StandardScopes.OpenId.Name,
StandardScopes.Profile.Name,
"api1",
"role",
StandardScopes.AllClaims.Name
}
}
Run Code Online (Sandbox Code Playgroud)
领域
return new List<Scope>
{
StandardScopes.OpenId,
StandardScopes.Profile,
new Scope
{
Name = "api1",
Description = "My API"
},
new Scope
{
Enabled = true,
Name = "role",
DisplayName = "Role(s)",
Description = "roles of user",
Type = ScopeType.Identity, …Run Code Online (Sandbox Code Playgroud) 我正在使用各种客户端实现IdentityServer4,其中一个客户端是一个Javascript应用程序,我已经实现了隐式流程进行身份验证,一切正常.
在我的Javascript应用程序上,我有一个登录按钮,一旦我点击按钮,我被重定向到IdentityServer,成功登录后,我被重定向回我的应用程序以及我的访问令牌.
现在我想要做的是,将登录名移到客户端,这样每个应用程序都可以拥有自己的登录UI(具有自己的主题).
app.js
function log() {
document.getElementById('results').innerText = "";
Array.prototype.forEach.call(arguments, function (msg) {
if (msg instanceof Error) {
msg = "Error:" + msg.message;
}
else if (typeof msg !== 'string') {
msg = JSON.stringify(msg, null, 2);
}
document.getElementById('results').innerHTML += msg + "\r\n";
});
}
document.getElementById("login").addEventListener('click', login, false);
document.getElementById('api').addEventListener('click', api, false);
document.getElementById("logout").addEventListener("click", logout, false);
//configure client
var config = {
authority: "http://localhost:5000",
client_id: "js",
redirect_uri: "http://localhost:5004/callback.html",
response_type: "id_token token",
scope: "openid profile api1 role",
post_logout_redirect_uri: "http://localhost:5004/index.html"
};
//init user manager …Run Code Online (Sandbox Code Playgroud)