使用令牌 API 和 angular 进行防伪 [英] Anti forgery with token API and angular

查看:31
本文介绍了使用令牌 API 和 angular 进行防伪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 SSO 登录和 .net 核心 Web API 开发 Angular 6 应用程序.该代码第一次在/token url 上命中后端,这是一个后期操作.在这种情况下我如何做防伪.请说明代币转账的流程

I am working on Angular 6 application with SSO login and .net core web API. The code hits the back end on /token url first time which is a post operation. How do I do the anti forgery in this scenario. Please explain the flow of token transfer

推荐答案

这个问题很老了,但我的解决方案可以帮助某人.什么对我们有用:

This question is old however my solution could help somebody. What worked for us:

  • 在 Angular FE 端使用 HttpXsrfTokenInterceptor 来设置 X-XSRF-TOKEN 标头.当然cookie必须包含XSRF-TOKEN

  • on Angular FE side HttpXsrfTokenInterceptor is used which is setting X-XSRF-TOKEN header. Of course cookie has to contain token under XSRF-TOKEN

在 .net 核心方面:基本上方法如上所述,使用 domstamand 的 方法.但是,这很重要,您必须将验证操作添加到中间件中.显然,使用您的自定义 middlaware 关闭验证由 .net 核心防伪服务完成.因此,在更新 Invoke 方法的代码后,应如下所示:

on .net core side: Basically approach describe above, using domstamand's approach. However, and this is important, you have to add validation action into the middleware. Apparently using your custom middlaware turn's off validation done OOB by .net core antiforgery service. So after update your code for Invoke method should looks like this:

 public Task Invoke(HttpContext context)
 {
     if (context.Request.Headers.ContainsKey("X-XSRF-TOKEN"))
     {
         _antiForgery.ValidateRequestAsync(context);
     }

     var tokens = _antiForgery.GetAndStoreTokens(context);
     context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions { 
         HttpOnly = false,
         Secure = true
     });

     return _next(context);
 }

我添加了对 X-XSRF-TOKEN 的检查以避免可能的问题,例如调用 GET 或 OPTIONS 预检时.

I added check for X-XSRF-TOKEN to avoid possible issues e.g. when GET or OPTIONS preflight check is called.

更新:我的解决方案的问题是,如果您不将 X-XSRF-TOKEN 包含到 HTTP 请求标头中,则验证根本不会执行.我试图找到解决办法.

Update: Problem with my solution is that if you don't include X-XSRF-TOKEN into the HTTP request header validation doesn't execute at all. I trying to find fix for that.

这篇关于使用令牌 API 和 angular 进行防伪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆