我一直在阅读(和观看视频)关于如何在使用带有大量ajax调用的MVC Core应用程序时最好地实现访问和刷新令牌.我想我做对了,但只是想知道是否有更好的方法来做到这一点.我将编辑此帖子,以便它可以作为任何寻找此信息的人的参考.
我的设置:我有一个包含大量JavaScript的MVC Core应用程序.JavaScripts使用ajax调用来检索json或调用操作.
由于我不希望我的用户能够使用cookie身份验证访问我的api,我使用app.Map将我的应用程序拆分为两部分.用户可以使用身份令牌访问视图的用户,以及需要访问令牌的用户.我还要添加一个cookie来保存我需要刷新访问令牌的时间.
Startup.cs(我删除了不重要的部分)
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = "Cookies",
AutomaticAuthenticate = true,
ExpireTimeSpan = TimeSpan.FromMinutes(60)
});
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
var oidcOptions = new OpenIdConnectOptions
{
AuthenticationScheme = "oidc",
SignInScheme = "Cookies",
Authority = LoginServerUrl,
RequireHttpsMetadata = false,
ClientId = "MyApp",
ClientSecret = "*****",
ResponseType = "code id_token",
SaveTokens = true,
Events = new OpenIdConnectEvents()
{
OnTicketReceived = async notification =>
{
notification.Response.Cookies.Append("NextAccessTokenRefresh", DateTime.Now.AddMinutes(30).ToString());
notification.Response.Cookies.Delete("AccessToken");
},
},
TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
NameClaimType = JwtClaimTypes.Name,
RoleClaimType = JwtClaimTypes.Role,
},
}; …Run Code Online (Sandbox Code Playgroud)