asp.net - .net core 2.2 无法从请求中检索 JWT 令牌
问题描述
我有一个使用带有 PageModel 的剃须刀页面的 asp.net Web 应用程序。我需要访问 REST Web 服务来获取 JWT 令牌
这是我在 Startup.cs 中的服务配置
services.AddIdentity<AppUser, AppUserRole>(cfg =>
{
cfg.User = new UserOptions() { };
cfg.User.RequireUniqueEmail = false;
cfg.SignIn.RequireConfirmedEmail = false;
})
.AddUserManager<AppUserManager<AppUser>>()
.AddUserStore<AppUserStore>()
.AddRoleStore<AppRoleStore>()
.AddDefaultTokenProviders();
services.Configure<TokenOptions>(Configuration.GetSection("TokenConf"));
var tokenConf = Configuration.GetSection("TokenConf").Get<TokenConf>();
services.Configure<AppConf>(Configuration.GetSection("AppConf"));
var appConf = Configuration.GetSection("AppConf").Get<AppConf>();
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidIssuer = tokenConf.Issuer,
ValidAudience = tokenConf.Audience,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(appConf.JWTSecretKey))
};
})
.AddCookie();
services.AddSingleton<IAuthenticationServiceProxy, AuthenticationServiceProxy>();
services.AddHttpContextAccessor();
services.AddMemoryCache();//alternatively we can use services.AddDistributedMemoryCache() and IDistributedCache cache
services.AddSession(options =>
{
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
services.AddOptions();
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc()
.AddRazorPagesOptions(options =>
{
options.Conventions.AuthorizePage("/Index");
options.Conventions.AuthorizePage("/Privacy");
options.Conventions.AllowAnonymousToPage("/Account/Login");
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
这是我的登录代码LoginModel : PageModel
public async Task<IActionResult> OnPostAsync(string returnUrl, string handler)
{
if (!ModelState.IsValid)
{
return Page();
}
var appUser = new AppUser() { UserName = UserLogin.Username };
var result = await _signInMgr.PasswordSignInAsync(appUser, UserLogin.Password, false, false);//_signInMgr.PasswordSignInAsync(UserLogin.Username, UserLogin.Password, false, false);
if (result.Succeeded)
{
var userTokenData = _authServPrx.GetTokenData(_appConf.Value.CslLink, UserLogin.Username, UserLogin.Password);
JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(userTokenData.Token);
var jwt = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
new OkObjectResult(jwt);
}
else
return BadRequest("Bad username or password"); //TODO: better return
return Page();
}
它不起作用,重定向不会发生,但是身份验证cookie确实被设置了。所以如果我然后手动去/Index
我到达
public void OnGet()
{
var accessToken = Request.Headers["Authorization"];
}
但是 accessToken 是空的。我只想重定向并能够以某种方式访问我的令牌。
难道我做错了什么?
解决方案
这取决于您要存储令牌、会话、缓存的位置......例如,您可以使用查询字符串传递:
if (result.Succeeded)
{
var userTokenData = _authServPrx.GetTokenData(_appConf.Value.CslLink, UserLogin.Username, UserLogin.Password);
JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(userTokenData.Token);
var jwt = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
return LocalRedirect(returnUrl+"?token="+jwt);
}
并在页面中获取令牌:
public void OnGet(string token)
{
}
推荐阅读
- scrapy - 运行 vagrant up 时无法重命名目录以在 Virtualbox 中保存设置文件
- matlab - 如何从 MATLAB 中的矩阵创建子矩阵(全部 5*5)?
- html - 内容未正确填充 CSS 网格列
- c - 遍历数组似乎不起作用
- sql - 为什么两个数字上的 UNION 比它们的总和更有效?
- python - QueryDict 中的 Django Post 请求中没有返回值
- sql-server - 在作业中使用 sp_add_jobstep 向该作业添加步骤实际上并没有运行添加的步骤?
- sql - 正则表达式 spring-jdbc (postgres) 中的命名参数
- git - BITBUCKET - 分享回购或转让回购
- for-loop - 阅读语句“if (x[i][0])”。