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
?)