MEAN-Angular路由超越NodeJS路由 [英] MEAN - Angular routes over-riding NodeJS routes

查看:87
本文介绍了MEAN-Angular路由超越NodeJS路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过PassportJS限制对客户端Angular应用的访问.

I'm trying to restrict access to the Client side Angular app via PassportJS.

基本上,我正在尝试路由尝试访问该应用程序的任何人以重定向到身份验证提供程序进行登录.但是,似乎角路由会覆盖NodeJS Express路由.

Basically i'm trying to route anyone trying to access the app to redirect to the authentication provider to login. But it appears the angular routes override the NodeJS Express routes.

因此,如果我转到"/",它将仅加载有角度的应用程序,而不重定向它们.对于使用与角向路线相同的路线的每条路线,情况都是相同的.

So if i go to '/' it'll just load the angular app and not redirect them. This is the same case for every route that uses the same route as the angular routes.

server.js代码段:

server.js snippet:

以下代码应将所有人重定向到Facebook.而是只加载角度索引页面.

The following code should redirect everyone to log into facebook. but instead it just loads the angular index page.

function checkAuthentication(req,res,next){
    if(req.isAuthenticated()){
        //if user is looged in, req.isAuthenticated() will return true 
        console.log("/ " + true);
        res.sendFile(path.join(__dirname, 'dist/index.html'));
    } else{
        console.log("/ " + false);
        res.redirect("/api/passport/login/facebook");
    }
}

app.get('/*', checkAuthentication ,(req, res) => {
});

Angular index.html代码段:

Angular index.html snippet:

index.html页面使用的路由与快速路由器中显示的路由相同.

The index.html page uses the same route as displayed in the express router.

  <base href="/">

假设我将index.html基本href更改为使用"/app/",如下所示:

Let's say i change the index.html base href to use '/app/' like so:

  <base href="/app/">

并在express中设置路由,以将登录的用户重定向到"/app/",如下所示:

and set up routing in express to redirect logged in users to '/app/' like so:

angular.route示例:

angular.route example:

app.use("/app", express.static(path.join(__dirname, 'dist')));

function checkAuthentication(req,res,next){
    if(req.isAuthenticated()){
        //if user is looged in, req.isAuthenticated() will return true 
        console.log("/app" + true);
        res.sendFile(path.join(__dirname, '../../dist/index.html'));
    } else{
        console.log("/app" + false);
        res.redirect("/api/passport/login/facebook");
    }
}

router.get('/app', checkAuthentication, (req, res) => {
    console.log("approuter hit");
});

module.exports = router;

并直接转到"/app".仍然会加载angular index.html页面,并且不会重定向您的登录.但是,如果您转到"/",它将重定向您的登录.

and go to '/app' directly. It'll still load the angular index.html page and not redirect you to log in. But if you go to '/' it will redirect you to log in.

如何停止对NodeJS Express路由的角度覆盖?

How do i stop angular over-riding my NodeJS express routes?

更新:

app.route.js代码段:

app.route.js snippet:

import { Routes } from '@angular/router';
import { HomeComponent } from './home';

export const ROUTES: Routes = [
  { path: '',      component: HomeComponent },
];

推荐答案

您必须在客户端(即Angular)实现AuthGuard和身份验证服务,该服务将充当客户端和服务器之间的通信器.还保留一个像isAuthenticated这样的变量来跟踪登录状态.

You have to implement the AuthGuard and a Authentication service at client side( i.e. Angular) which will act as a communicator between client and server. Also keep a variable like isAuthenticated to track the login status.

AuthGuard:

AuthGuard :

import { Injectable }     from '@angular/core';
import { CanActivate, CanActivateChild, Router }    from '@angular/router';

import { AuthenticationService } from './auth.service';

@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {

    constructor(private authService: AuthenticationService, private router: Router) {}
    canActivate() : boolean {
        console.log('AuthGuard#canActivate called ' + this.authService.isAuthenticated );
        return this.checkLoggedIn("random");
    }

    canActivateChild() : boolean {
        return this.canActivate();
    }

    checkLoggedIn(url: string): boolean {
        if (this.authService.isLoggedIn()) {
            return true;
        }
        this.authService.redirectUrl = url;
        this.router.navigate(['/login']);
        return false;
    }

}

AuthenticationService:

AuthenticationService:

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { Observable } from 'rxjs/Rx';
import { NgForm } from "@angular/forms";

import { AuthenticationApi } from "../../modules/authentication/authentication-api";
import { IUser } from "app/modules/authentication/user";
var headers = new Headers({ 'Content-Type': 'application/json' });
var options = new RequestOptions({ headers: headers });

@Injectable()
export class AuthenticationService implements AuthenticationApi {
  currentUser: IUser;
  redirectUrl: string;
  changePassoword: () => Observable<any>;
  forgotPassowrd: () => Observable<any>;

  isAuthenticated = false;
  constructor(private router: Router, private http: Http) {
    this.currentUser = null
  }

  isLoggedIn(): boolean {
    return !!this.currentUser;
  }

  logIn(logInUser:any): Observable<any> {
    console.log('UserService.signIn: ' + logInUser.userName + ' ' + logInUser.password + ' ' + logInUser.rememberMe);
    this.isAuthenticated = true;
    this.currentUser = {
      userName: logInUser.userName
    }
    return this.http.post('http://localhost:3000/auth/login',
      JSON.stringify(logInUser),
      options
    )
    .map((resp: Response) => resp.json())
    .catch(this.handleError);
    //return Observable.of({}).delay(2000);
    // return Observable.of({}).delay(2000).flatMap(x=>Observable.throw('Invalid User Name and/or Password'));
  }

  register(registerUser:any): Observable<any> {
    this.isAuthenticated = true;
    console.log(registerUser);
    return this.http.post('http://localhost:3000/auth/register',
      JSON.stringify(registerUser),
      options
    )
    .map((resp: Response) => resp.json())
    .catch(this.handleError);
      //this.router.navigate(['/signin']);
      //return Observable.of({}).delay(2000);
  }

  connectWithFacebook() :Observable<any> {
    this.isAuthenticated = true;
    //return Observable.of({}).delay(2000);
    return this.http.get('http://localhost:3000/auth/facebook')
    .map((resp: Response) => resp.json())
    .catch(this.handleError);
  }

  connectWithGoogle() :Observable<any> {
    this.isAuthenticated = true;
    //return Observable.of({}).delay(2000);
    return this.http.get('http://localhost:3000/auth/google')
    .map((resp: Response) => resp.json())
    .catch(this.handleError);
  }

  handleError(error: any) {
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
  }

  logOut(): Observable<any>{
    this.isAuthenticated = false;
    this.currentUser = null;
    this.router.navigate(['/login']);
    return Observable.of({})
  }

}

AuthenticationApi:常用的通信方法

AuthenticationApi: Common method to communicate

import { Observable } from 'rxjs';

export abstract class  AuthenticationApi {
    logIn : (loginUser:any) => Observable<any>;
    logOut : () => Observable<any>;
    register : (registerUser:any) => Observable<any>;
    connectWithFacebook : () => Observable<any>;
    connectWithGoogle : () => Observable<any>;
    changePassoword : () => Observable<any>;
    forgotPassowrd : () => Observable<any>;
}

这篇关于MEAN-Angular路由超越NodeJS路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆