As you have mentioned in question you are using IdentityServer4 as authorization provider
you can use the following way.
Adding a javascript client
Template for Javascript files 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';
});
}
use UserManagerClass to connect to 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);
At WebApi Part:
add a new client for javascript client.
// 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"
}
}
for more reference about how to add new client
Update for:
Ajax call to Identity Server and get 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": "[email protected]",
"password": "123456",
"client_id": "client",
"client_secret": "client123",
"scope": "scope1"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});