Angular5 Authentication to Api with jwt

我只是一个虾纸丫 提交于 2019-12-24 19:43:25

问题


I have an api accessible through an jwt token.

I have the expected result with postman and curl (curl -X POST http://localhost/api/login_check -d _username=login -d _password=pass) but not with angular.

Successful header request with postman:

POST /api/login_check 
cache-control: no-cache 
postman-token: 2b4a6be8-5c3d-4c66-99f9-daa49572d4bf 
user-agent: PostmanRuntime/7.1.1 
accept: */* 
host: localhost 
cookie: PHPSESSID=06u39ri0rr2i2sgdkjr451d6tj 
accept-encoding: gzip, deflate 
content-type: multipart/form-data; boundary=--------------------------825758704558259093486061 
content-length: 287

This is my configuration:

Angular CLI: 1.5.5
Node: 9.2.0
OS: linux x64
Angular: 5.1.1
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

@angular/cli: 1.5.5
@angular-devkit/build-optimizer: 0.0.36
@angular-devkit/core: 0.0.22
@angular-devkit/schematics: 0.0.42
@ngtools/json-schema: 1.1.0
@ngtools/webpack: 1.8.5
@schematics/angular: 0.1.11
@schematics/schematics: 0.0.11
typescript: 2.4.2
webpack: 3.8.1

And this is my service:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

const API_URL = 'http://localhost/api';

@Injectable()
export class SecurityService {

    constructor(private http: HttpClient) {
    }

    login(username: string, password: string) {
        let url = `${API_URL}/login_check`;

        return this.http.post(
            url,
            {_username: username, _password: password },
        ).subscribe(
            (response) => {
                console.log(response);
            }
        );
    }
}

This call return me an 401 error, invalid credentials. I had try to add header with contentType: 'application/x-www-form-urlencoded' but still the same error.

I am new to Angular, and do not understand how to proceed this authentification call.

Thanks


回答1:


It's probably because http.post posts the content as json, but your server is expecting x-www-form-urlencoded (which is what you are doing with the CURL -d option)

You need to set the correct headers

let options = {
headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')

};

And you need to set the correct body. Either using URLSearchParams

You can either do it manually, or use URLSearchParams

let body = new URLSearchParams();
body.set('_username', username);
body.set('_password', password);

this.http.post(this.loginUrl, body.toString(), options)

If you want to set the body manually, use

let body = '_username=username&_password=password';
this.http.post(this.loginUrl, body, options)


来源:https://stackoverflow.com/questions/48138869/angular5-authentication-to-api-with-jwt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!