Skip to content

Instantly share code, notes, and snippets.

@paxapy
Last active March 2, 2021 17:49
Show Gist options
  • Save paxapy/2b2dc687f1216e495d03c72c86b8394d to your computer and use it in GitHub Desktop.
Save paxapy/2b2dc687f1216e495d03c72c86b8394d to your computer and use it in GitHub Desktop.
angular + django auth
import { Observable, pipe, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable({providedIn: 'root'})
export class AuthGuard implements CanActivate {
constructor(private auth: AuthService) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
return this.auth.getToken().pipe(switchMap(token => of(!!token)));
}
}
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { AuthService } from './auth.service';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor (private auth: AuthService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (request.url.includes('api/obtain-token')) {
return next.handle(request)
}
const authReq = request.clone({
setHeaders: {
'Authorization': `Token ${this.auth.token}`
}
});
return next.handle(authReq)
}
}
import { Subject, Observable } from 'rxjs';
import { of } from 'rxjs';
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { CookieService } from 'ngx-cookie-service';
import { environment } from '@env/environment';
interface TokenResponse {
token: string
}
@Injectable({
providedIn: 'root'
})
export class AuthService {
public token: string;
public token$ = new Subject<string>();
constructor(private http: HttpClient, private cookie: CookieService) { }
public getToken(): Observable<string> {
if (this.token) {
return of(this.token)
}
const csrfToken = this.cookie.get('csrftoken')
if (!csrfToken) {
console.error('no cookies :c')
window.location.assign(`${environment.apiHost}/login/`)
}
const httpOptions = {
withCredentials: true,
headers: new HttpHeaders({'X-CSRFToken': csrfToken})
};
this.http.post(
`${environment.apiUrl}obtain-token-session/`, {}, httpOptions
).subscribe(
(response: TokenResponse) => {
this.token = response.token;
this.token$.next(this.token);
},
(error) => {
console.error(error)
window.location.assign(`${environment.apiHost}/login/`)
}
);
return this.token$.asObservable()
}
}
@paxapy
Copy link
Author

paxapy commented Feb 6, 2019

if you using apache, make sure you've set
WSGIPassAuthorization On
as described here: https://stackoverflow.com/a/33783391
also if you using ssl, you probably need to deactivate SessionAuthentication for unsafe methods, so set in corresponding views:

authentication_classes = (authentication.TokenAuthentication,)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment