[英]Retrieving a persistent token for Azure user access
我正在做一個項目,我需要訪問用戶郵箱(類似於 MS Flow 郵箱連接器的工作方式),當用戶在網站上時這很好,因為我可以從圖中訪問他們的郵箱和正確的權限請求。 我遇到的問題是我需要一個 web 作業來在用戶授予權限后繼續監視該用戶的郵件文件夾。 我知道我可以使用申請請求而不是委托請求,但我懷疑我的公司是否會簽署此協議。 有沒有辦法在用戶離開網站后持久持有 azure 令牌以訪問用戶信息......例如在網絡作業中?
編輯
也許我誤判了這一點,用戶在 web 應用程序中針對請求的 scope 的 Azure 應用程序進行身份驗證
let mailApp : PublicClientApplication = new PublicClientApplication(msalAppConfig);
let mailUser = mailApp.getAllAccounts()[0];
let accessTokenRequest = {
scopes : [ "User.Read", "MailboxSettings.Read", "Mail.ReadWrite", "offline_access" ],
account : mailUser,
}
mailApp.acquireTokenPopup(accessTokenRequest).then(accessTokenResponse => {
.....
}
這將返回經過身份驗證的正確響應。
然后我想在控制台應用程序/Web 作業中使用此用戶身份驗證,我嘗試使用它
var app = ConfidentialClientApplicationBuilder.Create(ClientId)
.WithClientSecret(Secret)
.WithAuthority(Authority, true)
.WithTenantId(Tenant)
.Build();
System.Threading.Tasks.Task.Run(async () =>
{
IAccount test = await app.GetAccountAsync(AccountId);
}).Wait();
但是 GetAccountAsync 總是返回 null?
@juunas 是正確的,根據需要刷新令牌並使用 AcquireTokenOnBehalfOf function。如果可能的話,他應該得到答案嗎?
使用我的代碼,返回的 idToken 可以在其他任何地方使用來訪問資源。 由於我的后端 WebJob 是連續的,我可以使用存儲的令牌訪問資源並在令牌過期前定期刷新令牌。
安加拉爾應用程序:
let mailApp : PublicClientApplication = new PublicClientApplication(msalAppConfig);
let mailUser = mailApp.getAllAccounts()[0];
let accessTokenRequest = {
scopes : [ "User.Read", "MailboxSettings.Read", "Mail.ReadWrite", "offline_access" ],
account : mailUser,
}
mailApp.acquireTokenPopup(accessTokenRequest).then(accessTokenResponse => {
let token : string = accessTokenResponse.idToken;
}
在后端,在 API、webJob 或控制台中:
var app = ConfidentialClientApplicationBuilder.Create(ClientId)
.WithClientSecret(Secret)
.WithAuthority(Authority, true)
.WithTenantId(Tenant)
.Build();
var authProvider = new DelegateAuthenticationProvider(async (request) => {
// Use Microsoft.Identity.Client to retrieve token
List<string> scopes = new List<string>() { "Mail.ReadWrite", "MailboxSettings.Read", "offline_access", "User.Read" };
var assertion = new UserAssertion(YourPreviouslyStoredToken);
var result = await app.AcquireTokenOnBehalfOf(scopes, assertion).ExecuteAsync();
request.Headers.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken);
});
var graphClient = new GraphServiceClient(authProvider);
var users = graphClient.Me.MailFolders.Request().GetAsync().GetAwaiter().GetResult();
最后我不得不放棄使用 ConfidentialClientApplicationBuilder,我仍然在前端使用 PublicClientApplicationBuilder 來獲得用戶的同意,但隨后我使用返回並接受刷新令牌的 oauth2/v2.0/token rest 服務處理其他所有事情。
這樣我就可以使用 PublicClientApplicationBuilder 向用戶征求郵箱同意 隨時使用 oauth2/v2.0/token 訪問用戶郵箱
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.