gpt4 book ai didi

asp.net-mvc - 将 JWT token 存储在 MVC 5 的 cookie 中

转载 作者:行者123 更新时间:2023-12-04 21:06:18 25 4
gpt4 key购买 nike

我想在我的 MVC 应用程序中进行 JWT 身份验证。我在 Web API 中创建授权 Web 服务,它正确返回 token 。之后,我尝试将 token 存储在 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");
}

但是现在我想将此 token 添加到每个请求的 header 中。所以我决定 Action 过滤器最适合实现这一目标。
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);
}
}

启动
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)
},

});

}
}

然后我只是标记了授权属性的 Controller 。当我用 POSTMAN 调用它时,它工作正常。

但是 MVC 中的操作过滤器总是在授权过滤器之后触发。所以我有问题:
  • 如何将 cookie 中的 token 添加到每个请求?这是好的做法吗?如果不是我应该怎么做?
  • 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;
    }
    }
    }

    最佳答案

    我找到了解决方案。我只是定制 OAuthBearerAuthenticationProvider提供者和此类内部我从 cookie 中检索 token ,然后将其分配给 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);
    }
    }

    然后在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

    });

    }
    }

    关于asp.net-mvc - 将 JWT token 存储在 MVC 5 的 cookie 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44994124/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com