我有一个 ASP.NET MVC 站点、IdentityServer4 主机和一个 Web API。
当我使用外部提供商(Facebook)登录 MVC 站点时,我登录得很好。从 MVC 站点我还可以正确使用 Web API。
然而,第二天,我仍然登录到 MVC 站点,但当我尝试访问 Web API 时,我收到“未授权异常”。
因此,尽管我仍然登录 MVC 站点,但我不再通过身份验证来从 MVC 站点内调用 Web API。
我想知道如何处理这种情况,以及应该如何配置 IdentityServer4。
- 为什么一天后我仍然登录 MVC 站点?如何配置?
- 如果我仍然登录 MVC 站点,为什么我仍然无法调用 Web API?
- 我可以同步过期时间吗?或者我应该如何处理这个问题?
MVC 应用程序的配置如下:
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.SignInScheme = "Cookies";
options.Authority = mgpIdSvrSettings.Authority;
options.RequireHttpsMetadata = false;
options.ClientId = mgpIdSvrSettings.ClientId;
options.ClientSecret = mgpIdSvrSettings.ClientSecret; // Should match the secret at IdentityServer
options.ResponseType = "code id_token"; // Use hybrid flow
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.Scope.Add("mgpApi");
options.Scope.Add("offline_access");
});
所以它使用混合流。
在 IdentityServer 中,MVC 客户端的配置如下:
new Client
{
EnableLocalLogin = false,
ClientId = "mgpPortal",
ClientName = "MGP Portal Site",
AllowedGrantTypes = GrantTypes.Hybrid,
// where to redirect to after login
RedirectUris = mgpPortalSite.RedirectUris,
// where to redirect to after logout
PostLogoutRedirectUris = mgpPortalSite.PostLogoutRedirectUris,
// secret for authentication
ClientSecrets = mgpPortalSite.ClientSecrets.Select(cs => new Secret(cs.Sha256())).ToList(),
AllowedScopes = new List<string>
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"mgpApi"
},
AllowOfflineAccess = true,
RequireConsent = false,
},
最后是网络 API:
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = mgpIdSvrSettings.Authority;
options.RequireHttpsMetadata = false;
options.ApiName = mgpIdSvrSettings.ApiName;
options.EnableCaching = true;
options.CacheDuration = TimeSpan.FromMinutes(10);
});