无法登录Angular2 / Django休息框架

时间:2017-03-30 14:40:42

标签: django angular authentication django-rest-framework

我正在使用以下Angular 2服务方法进行会话身份验证。

Unable to connect to server:

could not connect to server: Connection timed out (0x0000274C/10060)
Is the server running on host "192.168.195.95" and accepting
TCP/IP connections on port 5432?

结果:响应在标头setcookie值中包含 csrftoken sessionid ,但会被angular忽略。

使用凭据添加会导致CSRF无效令牌错误。

如何使用会话身份验证方案使用Angular 2和Django rest框架登录? Thnx提前!

1 个答案:

答案 0 :(得分:0)

我使用了Angang2的Django session auth:

loginUser (credentials: any): Observable<Profile> {
let headers = new Headers({ 'Content-Type': 'application/json'});
headers.append("X-CSRFToken", this.utils.getCookie('csrftoken'));

let options = new RequestOptions({ headers: headers, withCredentials: true });
return this.http.post(this.userUrl + 'auth/', credentials , options)
              .map(res => res.json())
              .catch(this.handleError);
}

在基于Django类的视图中:

@method_decorator(csrf_protect)
def post(self, request, format=None):

    user_data = request.data
    self.logger.info('Authenticating user {0}'.format(user_data['username']))


    user = authenticate(username=user_data['username'], password=user_data['password'])
    login(request, user)

我使用了Django休息框架。但我建议你使用django-jwt auth代替会话(更不用说痛苦了))。