正如您在问题中提到的那样,您使用 IdentityServer4 作为授权提供者
您可以使用以下方式。
Adding a javascript client
Javascript 文件模板 oidc-client JavaScript files
HTML
<html> <head>
<meta charset="utf-8" />
<title></title> </head> <body>
<button id="login">Login</button>
<button id="api">Call API</button>
<button id="logout">Logout</button>
<pre id="results"></pre>
<script src="oidc-client.js"></script>
<script src="app.js"></script> </body> </html>
JavaScript:
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';
});
}
使用UserManagerClass 连接到 IdentityServer4
var config = {
authority: "http://localhost:5000",
client_id: "js",
redirect_uri: "http://localhost:5003/callback.html",
response_type: "code",
scope:"openid profile api1",
post_logout_redirect_uri : "http://localhost:5003/index.html",
};
var mgr = new Oidc.UserManager(config);
在 WebApi 部分:
为javascript客户端添加一个新客户端。
// JavaScript Client
new Client
{
ClientId = "js",
ClientName = "JavaScript Client",
AllowedGrantTypes = GrantTypes.Code,
RequirePkce = true,
RequireClientSecret = false,
RedirectUris = { "http://localhost:5003/callback.html" },
PostLogoutRedirectUris = { "http://localhost:5003/index.html" },
AllowedCorsOrigins = { "http://localhost:5003" },
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"api1"
}
}
更多关于how to add new client的参考
更新:
Ajax 调用 Identity Server 并获取 Token
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost:5000/connect/token",
"method": "POST",
"headers": {
"content-type": "application/x-www-form-urlencoded",
"cache-control": "no-cache",
"postman-token": "a19f4ba3-b5aa-c61a-8078-c1a6ee39d5df"
},
"data": {
"grant_type": "password",
"username": "Test1@test.com",
"password": "123456",
"client_id": "client",
"client_secret": "client123",
"scope": "scope1"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});