问题
I am building web application using NodeJS for the server-side and Angular 2 for the client-side.
In the application I'm using ADFS to authenticate users.
The user browses to the website and automatically redirected to the ADFS authentication server. After the user completes the authentication, he redirects back to my application and I get the user data from the ADFS server.
I used passport-saml package to implement the authentication and it works fine.
The user is now stored at req.user.
Now I need to use user's data on the client side.
After a little research, I found that passing user's data from server to client can be as simple as :
router.get('/user/current', AuthMiddleware.requireLogin, (req: express.Request, res: express.Response) => {
return res.json(req.user);
});
This works as well.
Now for the client-side: I've created a service to fetch the authenticated user :
@Injectable()
export class AuthService {
private authUrl = 'http://localhost/api/user/current';
private currentUser: User;
constructor(private http: Http) {
this.getUser().subscribe(user => {
this.currentUser = user;
});
}
getUser(): Observable<User> {
return this.http.get(this.authUrl)
.map((res: Response) => res.json())
.catch(error => Observable.throw(error.json().error || 'Server Error'));
}
isAuthenticated(): boolean {
return !!this.currentUser;
}
}
So the getUser method returns an Observable with my user and I can use it in my client-side.
But my question is :
Should I inject the AuthService to each component which uses the authenticated user?
And if so, should I call getUser each time and wait for the Observable to return user's data, or should I use public parameter for the authenticated user?
(for example making the currentUser parameter public in the AuthService and then just use authService.currentUser?)
回答1:
You don't need to inject the AuthService into each component. What you want to do instead is guard the various routes in your application from activation unless a user has been authenticated. You must implement an AuthGuard that will have the AuthService injected.
Check out https://angular.io/docs/ts/latest/guide/router.html (search the page for "GUARD THE ADMIN FEATURE") for more information.
来源:https://stackoverflow.com/questions/41862070/angular-2-proper-use-of-authentication-service