代码拉取完成,页面将自动刷新
此库可使用OAuth 2.0和OpenID Connect对用户进行身份验证和授权,它还支持对OAuth 的PKCE扩展
借助此库,开发人员能够从 Microsoft 标识平台获取令牌,以便对用户进行身份验证并访问受保护的 Web API。 它可用于提供对 Microsoft Graph、其他 Microsoft API、第三方 Web API 或你自己的 Web API 的安全访问。
npm install @openid/appauth
MSAL
npm install @azure/msal-browser
<script type="text/javascript" src="https://alcdn.msauth.net/browser/2.30.0/js/msal-browser.min.js"></script>
服务器端示例DEMO代码下载
将@openid/appauth路径下的app与built文件上传到服务器,使用node或者Nginx挂载网站
将域名解析到该站点,并给网站申请配置SSL证书,否则会造成跨域错误
var openIdConnectUrl = 'https://login.microsoftonline.com/a7a2bee0-d8b2-4da5-8788-06ff4fdff7bb/v2.0';
var clientId = '04c02ae5-7005-4ed4-8ed6-5aa2c6d774ce';
var redirectUri = 'https://test2.chenyu520.cn/app/redirect.html';
"requestPermissions": [
{
"name": 'ohos.permission.INTERNET'
}
]
Web({ src: 'https://test2.chenyu520.cn', controller: this.controller })
.javaScriptAccess(true)
.domStorageAccess(true)
.mixedMode(this.mode)
.onConsole((event) => {
console.log('getMessage:' + event.message.getMessage());
return false;
});
window.objName.test(JSON.stringify(response));
testObj = {
test: (data) => {
prompt.showDialog({message:'Web---- ArkTs:' + data})
prompt.showDialog({message:'Web---- ArkTs tokenType:' + JSON.parse(data).tokenType})
return data;
}
}
onPageShow() {
this.controller.registerJavaScriptProxy({
object: this.testObj,
name: "objName",
methodList: ["test"],
});
this.controller.refresh()
}
注意:服务器需有node环境支持
将node_app上传到服务器,使用npm start启动服务,将域名解析到对应站点,并申请SSL证书(必备,否则PKCE过不去)
重定向URL选择单页应用程序,地址为:node_app所运行页面域名(一定要为https)
在app/authConfig.js中配置验证服务器相关信息,如下所示(此处配置地址以微软Azure平台为例)
const msalConfig = {
auth: {
clientId: "0df059c0-5ee9-484b-82e4-6da77db41fa8", //此处为应用注册完成后的应用程序id
authority: "https://login.microsoftonline.com/a7a2bee0-d8b2-4da5-8788-06ff4fdff7bb", //此处https://login.microsoftonline.com/租户id值
redirectUri: "https://test.chenyu520.cn", //此处为重定向URI
},
cache: {
cacheLocation: "sessionStorage",
storeAuthStateInCookie: false,
},
system: {
loggerOptions: {
loggerCallback: (level, message, containsPii) => {
if (containsPii) {
return;
}
switch (level) {
case msal.LogLevel.Error:
console.error(message);
return;
case msal.LogLevel.Info:
console.info(message);
return;
case msal.LogLevel.Verbose:
console.debug(message);
return;
case msal.LogLevel.Warning:
console.warn(message);
return;
}
}
}
}
};
const loginRequest = {
scopes: ["User.Read"]
};
const tokenRequest = {
scopes: ["User.Read", "Mail.Read"],
forceRefresh: false // Set this to "true" to skip a cached token and go to the server to get a new token
};
初始化对象
const msalInstance = new msal.PublicClientApplication(msalConfig);
var loginRequest = {
scopes: ["user.read", "mail.send"] // optional Array<string>
};
try {
msalInstance.loginRedirect(loginRequest);
} catch (err) {
// handle error
}
var request = {
scopes: ["Mail.Read"],
cacheLookupPolicy: CachePolicyLookup.Default
};
msalInstance.acquireTokenSilent(request).then(tokenResponse => {
// Do something with the tokenResponse
}).catch(error => {
if (error instanceof InteractionRequiredAuthError) {
return msalInstance.acquireTokenRedirect(request)
}
});
var headers = new Headers();
var bearer = "Bearer " + tokenResponse.accessToken;
headers.append("Authorization", bearer);
var options = {
method: "GET",
headers: headers
};
var graphEndpoint = "https://graph.microsoft.com/v1.0/me";
fetch(graphEndpoint, options)
.then(resp => {
//do something with response
});
var username = "test@contoso.com";
var currentAccount = msalInstance.getAccountByUsername(username);
var silentRequest = {
scopes: ["Mail.Read"],
account: currentAccount,
forceRefresh: false
};
var request = {
scopes: ["Mail.Read"],
loginHint: currentAccount.username
};
const tokenResponse = await msalInstance.acquireTokenSilent(silentRequest).catch(error => {
if (error instanceof InteractionRequiredAuthError) {
return msalInstance.acquireTokenRedirect(request)
}
});
const currentAccount = msalInstance.getAccountByHomeId(homeAccountId);
await msalInstance.logoutRedirect({
account: currentAccount,
postLogoutRedirectUri: "https://contoso.com/loggedOut"
});
支持 OpenHarmony API version 9 版本。
|---- OHOS_APP_appauth_js
| |---- entry # 示例代码文件夹
| |---- src
| |---- main
| |---- ets
| |---- pages
| |---- index.ets
| |---- MsalSample.ets # MSAL示例
| |---- OAuthSample.ets # OAuth示例
| |---- README.md # 安装使用方法
使用过程中发现任何问题都可以提 ISSUE给我们,当然,我们也非常欢迎你给我们发 PR 。
本项目基于 Apache License 2.0 ,请自由地享受和参与开源。
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。