前面的部分:

Identity Server 4 从入门到落地(一)—— 从IdentityServer4.Admin开始

Identity Server 4 从入门到落地(二)—— 理解授权码模式

Identity Server 4 从入门到落地(三)—— 创建Web客户端

Identity Server 4 从入门到落地(四)—— 创建Web Api

Identity Server 4 从入门到落地(五)—— 使用Ajax 访问 Web Api

认证服务和管理的github地址: https://github.com/zhenl/IDS4Admin

客户端及web api示例代码的github地址:https://github.com/zhenl/IDS4ClientDemo

前面我们在Web应用的页面上使用Ajax访问Web Api, 这种情况下,认证以及获取Access Token还是在后台进行的,而真正的单页面应用没有后台的参与,web服务器只起到host文件的作用,这部分我们编写简单的单页面应用,试验一下单页面访问受认证保护的Web Api。

我们参考Identity Server 4的官网示例编写这个单页面应用,将其中的认证服务器改为我们本地运行的认证服务http://localhost:4010,Web Api使用前面编写的简单示例,地址为http://localhost:5153。在编写之前,首先下载oidc的客户端,可以从github下载: https://github.com/IdentityModel/oidc-client-js/releases/tag/1.11.5 。我们使用编译完成的最终文件,将下载的文件解压,dist目录就是我们需要的文件。

首先使用Visual Studio 2022创建一个空的Asp.Net Core Web项目,我们使用这个项目作为html和js文件的宿主,除此之外不做其它工作。在项目目录下创建wwwroot目录,用于保存html和js文件,将下载的dist目录拷贝到这个目录中,目录名字改为oidc-client-js-1.11.5。然后在wwwroot下创建index.html、callback.html和app.js三个文件,文件的内容在后面填写。项目的结构如下:



然后修改lanuchSettings.json,项目的运行地址是http://localhost:5210:

{
"profiles": {
"IDS4ClientJS": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5210",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

接下来修改program.cs,使应用支持静态文件:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseDefaultFiles();
app.UseStaticFiles();
app.Run();

这样修改后,项目将Index.html作为缺省页面。

然后就是修改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-1.11.5/oidc-client.js"></script>
<script src="app.js"></script>
</body>
</html>

内容很简单,就是创建三个按钮,分别是登录、登出和调用Api。所实现的功能在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); var config = {
authority: "http://localhost:4010",
client_id: "js",
redirect_uri: "http://localhost:5210/callback.html",
response_type: "code",
scope: "openid profile myapi",
post_logout_redirect_uri: "http://localhost:5210/index.html",
};
var mgr = new Oidc.UserManager(config); 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:5153/WeatherForecast"; 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();
}

app.js使用oidc js客户端中定义的Oidc.UserManager实现对认证服务器的访问,完成认证和获取access token的工作,其配置在config 中定义,

var config = {
authority: "http://localhost:4010",
client_id: "js",
redirect_uri: "http://localhost:5210/callback.html",
response_type: "code",
scope: "openid profile myapi",
post_logout_redirect_uri: "http://localhost:5210/index.html",
};

最后,定义callback.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script src="oidc-client-js-1.11.5/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>

到此,客户端编写完成,我们还需要在认证服务管理中定义这个客户端,注意,在定义时需要选择单页面应用:



参考上面config中的定义设置客户端的其它部分:





最后一项工作是修改Web Api,增加这个网址的CORS设置:

builder.Services.AddCors(option => option.AddPolicy("cors",
policy => policy.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.WithOrigins(new[] { "https://localhost:7002", "http://localhost:5210" })));

好了,现在可以测试一下这个应用了,在Visual Studio中将解决方案的启动项目设置为多项目启动,同时启动JSClient和Web Api项目:

按F5运行,界面如下:



点击Login,会重定位到认证服务器的登录界面,登录完成后会显示用户的信息:



点击Call Api,会访问Web Api并显示结果:



到此,单页面客户端完成。相关代码可以从github下载: https://github.com/zhenl/IDS4ClientDemo

Identity Server 4 从入门到落地(六)—— 简单的单页面客户端的更多相关文章

  1. Identity Server 4 从入门到落地(八)—— .Net Framework 客户端

    前面的部分: Identity Server 4 从入门到落地(一)-- 从IdentityServer4.Admin开始 Identity Server 4 从入门到落地(二)-- 理解授权码模式 ...

  2. Identity Server 4 从入门到落地(三)—— 创建Web客户端

    书接上回,我们已经搭建好了基于Identity Server 4的认证服务和管理应用(如果还没有搭建,参看本系列前两部分,相关代码可以从github下载:https://github.com/zhen ...

  3. Identity Server 4 从入门到落地(七)—— 控制台客户端

    前面的部分: Identity Server 4 从入门到落地(一)-- 从IdentityServer4.Admin开始 Identity Server 4 从入门到落地(二)-- 理解授权码模式 ...

  4. Identity Server 4 从入门到落地(九)—— 客户端User和Role的解析

    前面的部分: Identity Server 4 从入门到落地(一)-- 从IdentityServer4.Admin开始 Identity Server 4 从入门到落地(二)-- 理解授权码模式 ...

  5. Identity Server 4 从入门到落地(十)—— 编写可配置的客户端和Web Api

    前面的部分: Identity Server 4 从入门到落地(一)-- 从IdentityServer4.Admin开始 Identity Server 4 从入门到落地(二)-- 理解授权码模式 ...

  6. Identity Server 4 从入门到落地(十一)—— Docker部署

    前面的部分: Identity Server 4 从入门到落地(一)-- 从IdentityServer4.Admin开始 Identity Server 4 从入门到落地(二)-- 理解授权码模式 ...

  7. Identity Server 4 从入门到落地(十二)—— 使用Nginx集成认证服务

    前面的部分: Identity Server 4 从入门到落地(一)-- 从IdentityServer4.Admin开始 Identity Server 4 从入门到落地(二)-- 理解授权码模式 ...

  8. Identity Server 4 从入门到落地(五)—— 使用Ajax访问Web Api

    前面的部分: Identity Server 4 从入门到落地(一)-- 从IdentityServer4.Admin开始 Identity Server 4 从入门到落地(二)-- 理解授权码模式 ...

  9. Identity Server 4 从入门到落地(四)—— 创建Web Api

    前面的部分: Identity Server 4 从入门到落地(一)-- 从IdentityServer4.Admin开始 Identity Server 4 从入门到落地(二)-- 理解授权码模式 ...

随机推荐

  1. 助你上手Vue3全家桶之Vue3教程

    目录 前言 1,setup 1.1,返回值 1.2,注意点 1.3,语法 1.4,setup的参数 2,ref 创建响应式数据 3,reactive 创建响应式数据 4,computed 计算属性 5 ...

  2. git与pycharm的使用详解(git+gitlab+pycham)

    前言 当自动化框架搭建出来后,需要多个人来使用框架,写自动化用例. 在这个阶段,我们不可能将写好的代码打包发给其他人,这样很麻烦,多人协作一点也不灵活. 这时候,就提现出了git的价值 一.下载安装 ...

  3. native连接远程mysql数据库

    1.环境 CentOS7.mysqld 8.0.19 2.登录数据库 #mysql -u root -p 2.修改root登录地址为%(任何IP) mysql> update user set ...

  4. vim 脚本,自动添加文件头部信息

    相信很多人编写脚本的时候都会在脚本头部写一些信息,记录文件生成时候,生成人姓名等 建议在自己的家目录下的 .vimrc 文件 下添加以下内容 [ autocmd BufNewFile *.sh exe ...

  5. Spring中bean的初始化和销毁几种实现方式

    Bean的生命周期 : 创建bean对象 – 属性赋值 – 初始化方法调用前的操作 – 初始化方法 – 初始化方法调用后的操作 – --- 销毁前操作 – 销毁方法的调用. [1]init-metho ...

  6. codeforces心得1---747div2

    codeforces心得1---747div2 cf div2的前AB题一般是字符串or数论的找规律结论题 因此标程极为精简 1.小窍门是看样例或者自己打表或造数据找规律 2.一些不确定的操作,可以化 ...

  7. 13.Fibonacci数

    描述 无穷数列1,1,2,3,5,8,13,21,34,55...称为Fibonacci数列,它可以递归地定义为 F(n)=1 ...........(n=1或n=2) F(n)=F(n-1)+F(n ...

  8. python实现模板匹配

    目录: (一)原理 (二)代码实现和几种常见的模板匹配算法 正文: (一)原理 在待检测图像上,从左到右,从上向下计算模板图像与重叠子图像的匹配度,匹配程度越大,两者相同的可能性越大. 作用有局限性, ...

  9. [atAGC046E]Permutation Cover

    每一个点都在一个排列中等价于所有排列覆盖所有位置 有解当且仅当满足$a_{y}\le 2a_{x}$(其中$a_{x}$为$a_{i}$的最小值,$a_{y}$为$a_{i}$的最大值) 证明:贪心选 ...

  10. [nowcoder5667H]Happy Triangle

    可以发现合法的答案有两种可能: 1.询问的$x$即为最大值(或之一),那么只需要找到x前两个数并判断即可 2.询问的$x$不是最大值,那么就要保证另外两边之差小于$x$,维护后缀中$的前驱k-k的前驱 ...