This solution is designed for authentication using JWT, but there are other solutions that do not use JWT.
This package (django-rest-framework-jwt) allows you to have auth endpoints for managing JWT in the Django Rest Framework. You will not have problems if you execute docs .
At the end of Angular2, you should have a login service that requested JWT from the server, using login credentials. It depends on your user model in Django.
This blog post is very helpful when using Angular2 JWT Authentication. You can check the authentication.service login function. I modified the code a bit to better match DRF-jwt.
let headers = new Headers({ 'Accept': 'application/json', 'Content-Type': 'application/json', }); let options = new RequestOptions({ headers: headers }); this.http.post(basePath + '/api-token-auth/', JSON.stringify({ username: username, password: password }), options) .map((response: Response) => { // login successful if there a jwt token in the response let token = response.json() && response.json().token; if (token) { // set token property this.token = token; // store username and jwt token in local storage to keep user logged in between page refreshes localStorage.setItem('id_token', token); // return true to indicate successful login return true; } else { // return false to indicate failed login return false; } }); // 'api-token-auth/' is the default endpoint with drf-jwt
This requests jwt from drf and stores it in localStorage.
From there, all of your HTTP requests requiring authentication should include an authorization header. There is an http wrapper that allows you to do this.
You can override the default configuration settings . The minimum configuration you need to override is that you must install globalHeaders. You do not need to change the name tokenName or tokenGetter. Just add Content-Type: application/json and Accept: application/json . (DRF will check the Accept header to decide which Renderer it should use.) You can also change the Prefix header to JWT because drf-jwt uses this prefix for the authorization header, or you can change it from drf-jwt settings.
source share