I
I
Ivan Stroykin2016-11-22 19:23:03
Angular
Ivan Stroykin, 2016-11-22 19:23:03

How to correctly combine angular 2 + django authentication?

Good day,
What is the most appropriate way to connect angular2 + django authentication? Better to check. Authentication now works by means: a session is created and the backend can give the necessary information, but what is the best way to check? To otherwise just redirect to the authorization page?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly, 2016-11-22
@StivinKing

All logic in Angular 2 is done through service classes. It is enough to perform 3 simple steps:
1. For example, in user.service.ts we will add information about the authorized user.
2. Let's create the AuthGuard service, which will be responsible for authorization. It must implement the CanActivate interface

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private userService: UserService) {}

  canActivate(route: ActivatedRouteSnapshot, state:RouterStateSnapshot): Promise<boolean>|boolean {
    return this.userService.isAuth;
  }
}

3. In the description of the paths, we indicate the class responsible for checking access:
{
    path: 'logout',
    component: LogoutComponent,
    canActivate: [AuthGuard]
  },
  {
    path: 'login',
    component: LoginComponent,
    canActivate: [GuestGuard]
  },

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question