在MVC 5中将JWT令牌存储在cookie中

TjD*_*haw 5 cookies asp.net-mvc jwt

我想在我的MVC应用中进行JWT身份验证。我在Web API中制作了授权Web服务,可以正确返回令牌。之后,我试图将令牌存储在cookie中。

 [HttpPost]
    public async Task<ActionResult> Login(LoginDto loginDto)
    {
        var token = await loginService.GetToken(loginDto);

        if (!string.IsNullOrEmpty(token))
        {
            var cookie = new System.Web.HttpCookie("token", token)
            {
                HttpOnly = true
            };
            Response.Cookies.Add(cookie);
            return RedirectToAction("Index", "Product");
        }
        return View("LoginFailed");
    }
Run Code Online (Sandbox Code Playgroud)

但是现在我想将此令牌添加到每个请求的标头中。因此,我认为动作过滤器将是实现此目标的最佳选择。

public class CustomActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var token = filterContext.HttpContext.Request.Cookies.Get("token");

        if (token != null)
            filterContext.HttpContext.Request.Headers.Add("Authorization", $"Bearer {token}");

        base.OnActionExecuting(filterContext);
    }
}
Run Code Online (Sandbox Code Playgroud)

启动

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        AutofacConfig.Configure();
        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

        ConfigureOAuth(app);
    }

    public void ConfigureOAuth(IAppBuilder app)
    {
        var issuer = System.Configuration.ConfigurationManager.AppSettings["issuer"];
        var audience = System.Configuration.ConfigurationManager.AppSettings["appId"];
        var secret = TextEncodings.Base64Url.Decode(System.Configuration.ConfigurationManager.AppSettings["secret"]);

        app.UseJwtBearerAuthentication(
            new JwtBearerAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Active,
                AllowedAudiences = new[] { audience },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                },

            });

    }
}
Run Code Online (Sandbox Code Playgroud)

然后我刚刚标记了哪个控制器授权属性。当我用POSTMAN调用它时,它工作正常。

但是,总是在授权过滤器之后触发MVC中的动作过滤器。所以我有问题:

  1. 如何从cookie向每个请求添加令牌?这是好习惯吗?如果没有,我该怎么办?
  2. csrf攻击和其他攻击如何?AntiForgeryTokenAttr是否可以完成工作?那ajax调用呢?

附加信息

这就是登录服务的样子。它只是对auth端点进行调用。

 public class LoginService : ILoginService
{
    public async Task<string> GetToken(LoginDto loginDto)
    {
        var tokenIssuer = ConfigurationManager.AppSettings["issuer"];
        using (var httpClient = new HttpClient {BaseAddress = new Uri($"{tokenIssuer}/oauth2/token")})
        {
            using (var response = await httpClient.PostAsync(httpClient.BaseAddress, new FormUrlEncodedContent(
                new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("username", loginDto.Username),
                    new KeyValuePair<string, string>("password", loginDto.Password),
                    new KeyValuePair<string, string>("grant_type", "password"),
                    new KeyValuePair<string, string>("client_id", ConfigurationManager.AppSettings["appId"])
                })))
            {
                var contents = await response.Content.ReadAsStringAsync();

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var deserializedResponse =
                        new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(contents);

                    var token = deserializedResponse["access_token"];

                    return token;
                }
            }
            return null;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

TjD*_*haw 3

我找到了解决方案。我只是制作自定义OAuthBearerAuthenticationProvider提供程序,并在这个类中从 cookie 检索令牌,然后将其分配给context.Token

public class MvcJwtAuthProvider : OAuthBearerAuthenticationProvider
{
    public override Task RequestToken(OAuthRequestTokenContext context)
    {
        var token = context.Request.Cookies.SingleOrDefault(x => x.Key == "token").Value;

        context.Token = token;
        return base.RequestToken(context);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在startup.cs里面

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        AutofacConfig.Configure();
        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

        ConfigureOAuth(app);
    }

    public void ConfigureOAuth(IAppBuilder app)
    {
        var issuer = System.Configuration.ConfigurationManager.AppSettings["issuer"];
        var audience = System.Configuration.ConfigurationManager.AppSettings["appId"];
        var secret = TextEncodings.Base64Url.Decode(System.Configuration.ConfigurationManager.AppSettings["secret"]);

        app.UseJwtBearerAuthentication(
            new JwtBearerAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Active,
                AllowedAudiences = new[] { audience },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                },
                Provider = new MvcJwtAuthProvider() // override custom auth

            });

    }
}
Run Code Online (Sandbox Code Playgroud)