我有我的reactJS SPA,我的Web api托管在Azure VM中。我将 APIM 放在 VM 前面,APIM 根据 B2C 验证 token 以进行授权。 在B2C用户流程中,我将 token 生命周期设置为5分钟;
在 SPA 中,当我第一次登录时,它运行良好,我可以毫无问题地调用 Web API。但是,后来我遇到了两个问题:
即使我将 token 生命周期设置为 5 分钟,但 5 分钟后它仍然有效; 13、14分钟左右失效;太奇怪了;
token 刷新后,新的访问 token 无法通过APIM;它返回 401 错误;我可以验证新 token 是否在 session 存储中就位;刷新过程成功
这是我最初用于登录的loginRequest
:
export const loginRequest = {
scopes: ['openid', 'profile'],
};
这是我用来刷新 token 的代码:
export const msalInstance = new PublicClientApplication(msalConfig);
export const GetAzureB2CAccessToken = async () => {
const activeAccount = msalInstance.getActiveAccount(); // This will only return a non-null value if you have logic somewhere else that calls the setActiveAccount API
const accounts = msalInstance.getAllAccounts();
if (!activeAccount && accounts.length === 0) {
/*
* User is not signed in. Throw error or wait for user to login.
* Do not attempt to log a user in outside of the context of MsalProvider
*/
throw new Error('user is not signed in;');
}
var request = {
scopes: [
'openid',
'profile',
'https://devjohn1.onmicrosoft.com/123qwe-19eb-fff-qqqq-123qwe123qwe/johnapp_api',
],
account: activeAccount || accounts[0],
};
const tokenResponse = await msalInstance.acquireTokenSilent(request);
return tokenResponse.accessToken;
};
有什么想法吗?
最佳答案
我创建了一个 Azure AD B2C 用户流并将 token 生命周期设置为 5 分钟,如下所示:
现在,当我通过 Postman 生成 token 时, token 生命周期设置为 5 分钟,如下所示:
https://rukb2c.b2clogin.com/rukb2c.onmicrosoft.com/B2C_1_testruk/oauth2/v2.0/token
client_id:ClientID
scope:https://rukb2c.onmicrosoft.com/ClientID/test.read offline_access openid
grant_type:authorization_code
code_verifier:S256
code:code
Even though I set the token lifetime to 5 minutes, it is still valid after 5 minutes; It only becomes invalid at around 13 or 14 minutes; So weird
如果根据 token 生命周期策略, token 没有过期,则可能是由于时钟偏差造成的,默认值为 5 分钟。
根据 @Kid_Learning_C 的评论,如果您希望 token 在精确时间到期,请将 ClockSkew
设置为零。
services.AddAuthentication("Bearer").AddJwtBearer("Bearer", options =>
{
options.Authority = "https://xxxx";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
});
引用:
关于azure - B2C token 生命周期不起作用,新的访问 token 无法通过 APIM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76654723/