[one by one series] identityserver4 (V) creating JavaScript client

DDGarfield 2022-06-23 18:59:50 阅读数:174

seriesidentityserver4identityservercreatingjavascript

according to OAuth2.0 Of 4 There are two ways of authorization , The next step is to introduce hidden (implicit), Corresponding OpenId Connect Flow Of Implicit Flow, however IdentityServer4 The latest official document doesn't say , Just gave Adding a JavaScript client Chapter of , And according to the internal code , Or the authorization code , Not used Implicit Flow Protect SPA, I don't know why , But we still follow the latest official documents , Previous documents , A version number is relase Documents , Yes Implicit Flow Introduction to , Children's shoes of interest , You can read it , The latest document number is latest, Compare the actual code from the application , It's not that different , The only difference may be the principle , But do not capture packets to check related messages , Can't feel it .

1. Create client

Here we follow the official tutorial , Use ASP.NET Core Empty item , Use the built-in server to host client static files .

1.1 Create project

md JavaScript
cd JavaScript
dotnet new web
dotnet sln add .\JavaScript\JavaScript.csproj

1.2 modify launchSettings.json

{
"profiles": {
"JavaScript": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "http://localhost:6003",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

1.3 add to ‘ Static file middleware ’

The project is designed to run on the client , We just need ASP.NET Core Provide the static... That make up our application HTML and JavaScript file , The static file middleware is designed for this purpose .

Register the static file middleware , Also delete other code .

Startup.Configure

public void Configure(IApplicationBuilder app)
{
app.UseDefaultFiles();
app.UseStaticFiles();
}

This middleware will now provide... For the application **~/wwwroot** Static files in folders . This is where we will place HTML and JavaScript Where the papers are . This directory does not exist in an empty project , So you need to create this directory .

1.4 oidc-client library download

In the first chapter , We used a library to handle OpenID Connect agreement , stay JavaScript in , We also need similar Libraries , But now we need this library to be able to JavaScript And the browser is running ( because node.js Server side ),https://github.com/IdentityModel/oidc-client-js

We use it npm download

npm i oidc-client
copy .\node_modules\oidc-client\dist\* .\wwwroot\

1.5 add to html and js file

Two html File and one except the one above oidc-client In addition to the js The documents comprise us JavaScript application (SPA)

  • index.html
  • callback.html
  • app.js

index.html

<!DOCTYPE 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>

3 A login button , Introduce two js file

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';
});
}
//register click event handlers to the three buttons
document.getElementById("login").addEventListener("click", login, false);
document.getElementById("api").addEventListener("click", api, false);
document.getElementById("logout").addEventListener("click", logout, false);
//UserManager from the oidc-client to manage the OpenID Connect protocol
var config = {
authority: "http://localhost:5001",
client_id: "js",
redirect_uri: "http://localhost:6003/callback.html",
response_type: "code",
scope: "openid profile api1",
post_logout_redirect_uri: "http://localhost:6003/index.html",
};
var mgr = new Oidc.UserManager(config);
/*
* UserManager provides a getUser API to know if the user is
* logged into the JavaScript application.
* It uses a JavaScript Promise to return the results asynchronously.
* The returned User object has a profile property which contains
* the claims for the user.
* Add this code to detect if the user is logged into
* the JavaScript application:
*/
mgr.getUser().then(function (user) {
if (user) {
log("User logged in", user.profile);
}
else {
log("User not logged in");
}
});
function login() {
mgr.signinRedirect();
}
function api() {
mgr.getUser().then(function (user) {
var url = "http://localhost:6001/api/identity";
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = function () {
log(xhr.status, JSON.parse(xhr.responseText));
}
xhr.setRequestHeader("Authorization", "Bearer " + user.access_token);
xhr.send();
});
}
function logout() {
mgr.signoutRedirect();
}
  • Yes 3 Buttons to listen , And trigger different events :addEventListener
    • Sign in
    • sign out
    • call api

callback.html

This HTML The file is where the user logs in IdentityServer Designated after redirect_uri page , It will be associated with IdentityServer complete OpenID Connect Protocol login handshake . This code is all written by us in app.js Used in UserManager Class provides . After login , We can redirect users back to the main page index.html.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script src="oidc-client.js"></script>
<script>
new Oidc.UserManager({response_mode:"query"}).signinRedirectCallback().then(function() {
window.location = "index.html";
}).catch(function(e) {
console.error(e);
});
</script>
</body>
</html>

2. stay IdentityServer Register client

The client application is ready , Like other clients , need IdentityServer Add client in

// JavaScript Client
new Client
{
ClientId = "js",
ClientName = "JavaScript Client",
// Notice here ,GrantTypes It's a choice Code
// GrantTypes.Implicit,
AllowedGrantTypes = GrantTypes.Code,
RequireClientSecret = false,
RedirectUris = { "http://localhost:6003/callback.html" },
PostLogoutRedirectUris = { "http://localhost:6003/index.html" },
AllowedCorsOrigins = { "http://localhost:6003" },
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"api1"
}
}

3. allow ajax Cross-domain calls webapi

This needs to be in webapi Add cross domain configuration to the project

Startup.ConfigureServices

services.AddCors(options =>
{
// this defines a CORS policy called "default"
options.AddPolicy("default", policy =>
{
policy.WithOrigins("http://localhost:6003")
.AllowAnyHeader()
.AllowAnyMethod();
});
});

add to CORS middleware

public void Configure(IApplicationBuilder app)
{
app.UseRouting();
app.UseCors("default");
// ...
}

More cross domain configurations , Refer to official documentation

4. test

function IdentityServer

cd .\IdentityServer\
dotnet run

function webapi

cd .\webapi\
dotnet run

VS function SPA

Start the built-in server , Loading static files

Login successful

call api

Sign out

Reference link

http://docs.identityserver.io/en/latest/quickstarts/4_javascript_client.html

版权声明:本文为[DDGarfield]所创,转载请带上原文链接,感谢。 https://qdmana.com/2022/174/202206231758268014.html