Я пытаюсь создать инструмент автоматизации электронной почты Outlook. Для этого нужно сделать что-то, например, отправить электронное письмо в папку для пользователя в указанное время. Microsoft позволяет сторонним apis запускать apis от имени пользователя от имени пользователя через auth2. Я могу получить необходимый токен доступа, но мне нужен токен refre sh, чтобы вызывать код от имени пользователя, не заставляя его входить в систему каждый час.
В настоящее время я использую библиотеку аутентификации Microsoft javascript для получения токенов. Из того, что я прочитал, кажется, что у refre sh должна быть автономная область действия в запросе токена. С кодом ниже, я могу получить ответ с токеном доступа, но я все еще не могу получить токен доступа.
![enter image description here](https://i.stack.imgur.com/AMgNz.png)
const tokenRequest = {
scopes: [
"https://graph.microsoft.com/Mail.ReadWrite",
"https://graph.microsoft.com/mail.send",
"https://graph.microsoft.com/offline_access"
]
};
const hostname = "http://localhost:5000";
const backendServerAdress = "http://localhost:8050";
var xhr = new XMLHttpRequest();
xhr.open("POST", backendServerAdress, true);
xhr.setRequestHeader("Content-Type", "application/json");
const msalConfig = {
auth: {
clientId: "something",
redirectUri: hostname + "/homepage/index.html"
}
};
var loginRequest = {
scopes: ["Mail.ReadWrite", "mail.send", "offline_access"] // optional Array<string>
};
const TOKEN_ID = "token_id";
const msalInstance = new Msal.UserAgentApplication(msalConfig);
msalInstance.handleRedirectCallback((error, response) => {
console.log("redirect callback done");
});
async function redirectToDashboard() {
console.log("redirect to dashboard");
// var response = await requestTokenSilent();
var response;
if (!response || !response.status == 200) {
response = await requestTokenPopup();
}
if (response && response.status == 200) {
xhr.send(
JSON.stringify({
firstname: "something",
lastname: "something",
accessToken: "something"
})
);
location.href = hostname;
} else {
console.log("Unable to acquire token");
}
}
function redirectLogin() {
console.log("redirect called");
if (!msalInstance.getAccount()) {
return msalInstance
.loginRedirect(loginRequest)
.then(response => {
console.log(response);
return response;
})
.catch(err => {
console.log("Authentication error: ", err);
});
}
if (msalInstance.getAccount()) {
redirectToDashboard();
}
}
async function requestTokenSilent() {
console.log("requestTokenSilent");
if (msalInstance.getAccount()) {
return msalInstance
.acquireTokenSilent(tokenRequest)
.then(response => {
localStorage.setItem(TOKEN_ID, response.accessToken);
console.log("response reached: ", response);
resolve(response);
})
.catch(err => {
if (err.name === "InteractionRequiredAuthError") {
alert("Authentication failed try again");
}
});
}
}
async function requestTokenPopup() {
console.log("requestTokenPopup");
if (msalInstance.getAccount()) {
return msalInstance
.acquireTokenPopup(tokenRequest)
.then(response => {
localStorage.setItem(TOKEN_ID, response.accessToken);
return response;
})
.catch(err => {
console.log(err);
if (err.name === "InteractionRequiredAuthError") {
alert("Authentication failed try again");
}
});
}
}