首页 > 解决方案 > .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 是空的。我只想重定向并能够以某种方式访问​​我的令牌。
难道我做错了什么?

标签: asp.netasp.net-corejwtasp.net-core-2.0

解决方案


这取决于您要存储令牌、会话、缓存的位置......例如,您可以使用查询字符串传递:

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)
{

}

推荐阅读