要在没有用户交互的情况下获取有效的图形令牌,您可以使用以下请求。但请注意,这意味着在您的客户端代码中存储了客户端密钥。这样,用户就可以请求有效的应用程序令牌,并可以访问应用程序范围内允许的任何内容。
因此,就像名称已经说明的那样,客户端密钥应该保密,并且不应在客户端站点上的代码中使用。更好的是拥有一个自己的 REST api,它发送以下请求并将令牌返回到您的角度应用程序。如何保护此 api 的安全取决于您。
非交互式用户令牌
var settings = {
"async": true,
"crossDomain": true,
"url": `https://login.microsoftonline.com/${tenantId}/oauth2/token`,
"method": "POST",
"headers": {
"content-type": "application/x-www-form-urlencoded",
"cache-control": "no-cache"
},
"data": {
"client_id": `${clientId}`,
"client_secret": ${clientSecret}``,
"resource": "https://graph.microsoft.com/",
"username": `${username}`,
"password": `${password}`,
"grant_type": "password",
"scope": "openid"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
不过,您可以将上述请求转换为您的具体语言。但作为一项特殊服务,我将上述代码重写为您给定的代码(未经测试):
getToken() {
var msFormData = new FormData();
msFormData.append('clientId', `${clientId}`);
msFormData.append('client_secret', `${clientSecret}`);
msFormData.append('resource', 'https://graph.microsoft.com');
msFormData.append('username', `${username}`);
msFormData.append('password', `${password}`);
msFormData.append('grant_type', 'password');
msFormData.append('scope', 'openid');
return this.http.post(`https://login.microsoftonline.com/${tenantId}/oauth2/token`, msFormData);
}
非交互式应用程序令牌
var settings = {
"async": true,
"crossDomain": true,
"url": `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`,
"method": "POST",
"headers": {
"content-type": "application/x-www-form-urlencoded",
"cache-control": "no-cache",
},
"data": {
"grant_type": "client_credentials",
"scope": "https://graph.microsoft.com/.default",
"client_id": `${clientId}`,
"client_secret": `${clientSecret}`
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
您还可以直接使用变量本身,而不是使用仅包含变量的反引号字符串。但我选择这种风格是为了更好地强调这些参数必须由您自己提供。