Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add token in http request angular

I am tring to do login using angluar and spring boot. I use JWT authentication and after successful athentication i got token in response. After submitting the login i am redirecting to the another url but i need to add bearer token into the url otherwise it returns anonymousUser. I am new to angular please tell me how can i add token into request.

LoginService

loginUser(data: Student): Observable<any> {
    const url = '/login';
    let headers = new HttpHeaders();
    headers = headers.set('Content-Type', 'application/text; charset=utf-8');
    return this.httpClient.post(this.serverUrl + url, data, {responseType: 'text' as 'json'});
}

getuserInfo(): Observable<any> {
    const url = '/userinfo';
    return this.httpClient.get(this.serverUrl + url);
}

Login form submit

Loginform

submitForm(submission: any): void {
    console.log(submission);
    if (submission && submission.submit) {
        delete submission.submit;
    }
    this.loginService.loginUser(submission)
        .subscribe(result => {
            console.log(result);
            this.userinfo();
        }, err => {
            alert(err);
        });
}

userinfo() {
    this.loginService.getuserInfo()
    .subscribe(result => {
        console.log(result);
    }, err => {
        alert(err);
    });
}

Response

How can i add this token in userinfo please help me.


2 Answers

Store your token in localStorage:

localStorage.setItem('token', 'yourToken');

and use interceptor to set the token in request:

@Injectable({
    providedIn: 'root'
})
export class UserEmulationInterceptor implements HttpInterceptor {

    private readonly token: string;

    constructor() {
        this.token = localStorage.getItem('your_sso_token');
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (this.token) {
            const modReq = req.clone({
                setHeaders: {
                    'your_sso_token': this.token
                }
            });
            return next.handle(modReq);
        }
        return next.handle(req);
    }
}
like image 136
huan feng Avatar answered Aug 09 '26 18:08

huan feng


In userinfo() function store the token in localStorage

e.g localStorage.setItem('token', 'yourToken') and then in loginUser(data: Student) retrieve the value like

const token = localStorage.getItem('token')

// Add a header
header.set('Authorization', `Bearer ${token}`)

If you using this on more request then it would best to investigate HttpInterceptor.

like image 45
Spiderman Avatar answered Aug 09 '26 19:08

Spiderman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!