即使withCredentials在POST请求中为true,Angular也不会发送Set-Cookie中收到的Cookie。

时间:2018-08-23 12:56:35

标签: angular csrf

嗨,我也面临着同样的问题。我正在研究MEAN-Stack应用程序。所以我需要每种形式的scrf令牌来防止csrf攻击。为此,我必须先发送GET请求,以获取csrf令牌并保存在表单中,然后使用该令牌提交表单,但截至目前,我正在获取csrf令牌作为响应,并在cookie中获取csrf令牌。但在POST请求中,cookie csrf令牌未发送。和服务器都需要表单令牌和cookie令牌来授权POST请求。

请参阅我的代码,请帮助我。

server.js

var csrf = require('csurf');
var cors = require('cors');
var indexRouter = require('./routes/index');
var app = express();
var corsOptions = {
   origin: 'http://localhost:4200',
   optionsSuccessStatus: 200,
   credentials:true
}
app.use(cors(corsOptions));
app.use(express.static(path.join(__dirname, 'public')));
app.use(csrf({
cookie: {
    httpOnly: false,
    domain:'localhost',
    secure: false,
    key: 'XSRF-TOKEN',
    path: '/',
    expires: new Date(Date.now() + 60 * 60 * 1000)
}
}));
app.use('/api', indexRouter);

Index.js

router.get('/csrf', function (req, res, next) {
res.json({csrfTokenFromServer:req.csrfToken()})
})

客户端

component.js

获取请求

getcsrf() {

    this.userService.csrf().subscribe((res) => {
        console.log(res)
        this.credentials._csrf = res.csrfTokenFromServer;
        //console.log(res.headers);
    }, (error) => {
        console.log(error)
    })
}

POST请求

 saveUser() {

    const httpOptions = {
        headers: new HttpHeaders({ 'Content-Type': 'application/json' }),

        withCredentials: true,
        observe: 'response' as 'response'
    };
    this.userService.login(this.credentials,httpOptions).subscribe((response) => {
        console.log(response)
    }, (error) => {
        console.log(error)
    })
}

userservices.js

public csrf(): Observable<any> {
    const httpOptions = {
        headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
        withCredentials: true 
    };
    return this.http.get<any>(this.api_url + 'csrf',httpOptions);
}

public login(user,httpOptions): Observable<any> {
    return this.http.post<any>(this.api_url + 'login',user,httpOptions);
}

请帮助我。

0 个答案:

没有答案