.net core 2.2无法从请求中检索JWT令牌

时间:2019-07-11 12:05:51

标签: asp.net asp.net-core jwt asp.net-core-2.0

我有一个ASP.net Web应用程序,该应用程序将剃须刀页面与PageModel一起使用。我需要访问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为空。 我只想重定向并能够以某种方式访问​​我的令牌。
 我在做错什么吗?

1 个答案:

答案 0 :(得分: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)
{

}