Angular2重定向到登录页面 [英] Angular2 redirect to login page

查看:4342
本文介绍了Angular2重定向到登录页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自Asp.Net MVC的世界里,用户试图访问他们没有被授权将自动重定向到登录页面的页面。

我试图重现Angular2此行为。我来到了防空火炮装饰@CanActivate,但它导致部分未被呈现在所有,任何重定向。

我的问题是:


  • 是否Angular2提供了一种方式来实现这一行为?

  • 如果是这样,如何​​?它是一个好的做法呢?

  • 如果不是,这将是在Angular2处理用户授权的最佳实践?


解决方案

更新:我已经出版了一本完整的骨架的角2项目,在Github上的OAuth2整合,显示在行动下面提到的指令。

做的是,通过使用指令的一种方式。不同于您插入到您的网页角2 组件,它基本上是新的HTML标签(关联code),定语指令是,你把一个属性标签导致发生一些行为。这里 文档。

自定义属性的presence导致事情发生到组件您放置在指令(或HTML元素)考虑这个指令我用我的当前Angular2 /应用的OAuth2:

 进口{指令,}的OnDestroy从'angular2 /核心;
进口{} AuthService从'../services/auth.service';
进口{ROUTER_DIRECTIVES,路由器,位置}从angular2 /路由器;@指示({
    选择:[保护]'
})
出口类ProtectedDirective实现的OnDestroy {
    私人子:任何= NULL;    构造函数(私人authService:AuthService,私人路由器:路由器,私人的位置:位置){
        如果(!authService.isAuthenticated()){
            this.location.replaceState('/'); //清除浏览器的历史,使他们无法与后退按钮导航
            this.router.navigate(['PublicPage']);
        }        this.sub = this.authService.subscribe((VAL)=> {
            如果(!val.authenticated){
                this.location.replaceState('/'); //清除浏览器的历史,使他们无法与后退按钮导航
                this.router.navigate(['LoggedoutPage']); //告诉他们,他们已经被注销(在某种程度上)
            }
        });
    }    ngOnDestroy(){
        如果(this.sub!= NULL){
            this.sub.unsubscribe();
        }
    }
}

这使得使用身份验证服务,我写来确定用户是否已经登录和也同意以验证事件,以便它可以出来踢的用户,如果他或她登录出或超时。

您可以做同样的事情。你会创造像我这样的指令,检查的必要的cookie或指示用户进行身份验证的其他状态信息的presence。如果他们没有那些你正在寻找的标志,将用户重定向到您的主要公共网页(像我一样),或者你的OAuth2服务器(或其他)。你会把该指令属性需要被保护的任何组件。在这种情况下,它可以被称为保护像在指令我上面粘贴。

 <会员专属-INFO [保护]>< /仅限会员-信息>

那么你将要导航/你的应用程序中的用户重定向到一个登录视图,并办理认证那里。你必须对当前的路线改为你想要做的之一。因此,在这种情况下,你会使用依赖注入来获得在路由器对象你的指令的构造函数()函数,然后使用导航()方法将用户发送到您的登录页面(如在我上面的例子)。

这假定您有一系列路线某处控制&LT的;路由器出口> 标签,看起来这样的事情,也许是:

  @RouteConfig([
    {路径:'/ loggedout',名称:'LoggedoutPage',成分:LoggedoutPageComponent,useAsDefault:真正},
    {路径:'/公',名称:'PublicPage',成分:PublicPageComponent},
    {路径:'/保护',名称:'ProtectedPage',成分:ProtectedPageComponent}
])

相反,如果你需要将用户重定向到一个外部 URL,比如你的OAuth2服务器,那么你将有你的指令做一些这样的:

<$p$p><$c$c>window.location.href=\"https://myserver.com/oauth2/authorize?redirect_uri=http://myAppServer.com/myAngular2App/callback&response_type=$c$c&client_id=clientId&scope=my_scope

I come from the Asp.Net MVC world where users trying to access a page they are not authorized are automatically redirected to the login page.

I am trying to reproduce this behavior on Angular2. I came accross the @CanActivate decorator, but it results in the component not rendering at all, no redirection.

My question is the following:

  • Does Angular2 provide a way to achieve this behaviour?
  • If so, how? Is it a good practice?
  • If not, what would be the best practice for handling user authorization in Angular2?

解决方案

Update: I've published a full skeleton Angular 2 project with OAuth2 integration on Github that shows the directive mentioned below in action.

One way to do that would be through the use of a directive. Unlike Angular 2 components, which are basically new HTML tags (with associated code) that you insert into your page, an attributive directive is an attribute that you put in a tag that causes some behavior to occur. Docs here.

The presence of your custom attribute causes things to happen to the component (or HTML element) that you placed the directive in. Consider this directive I use for my current Angular2/OAuth2 application:

import {Directive, OnDestroy} from 'angular2/core';
import {AuthService} from '../services/auth.service';
import {ROUTER_DIRECTIVES, Router, Location} from "angular2/router";

@Directive({
    selector: '[protected]'
})
export class ProtectedDirective implements OnDestroy {
    private sub:any = null;

    constructor(private authService:AuthService, private router:Router, private location:Location) {
        if (!authService.isAuthenticated()) {
            this.location.replaceState('/'); // clears browser history so they can't navigate with back button
            this.router.navigate(['PublicPage']);
        }

        this.sub = this.authService.subscribe((val) => {
            if (!val.authenticated) {
                this.location.replaceState('/'); // clears browser history so they can't navigate with back button
                this.router.navigate(['LoggedoutPage']); // tells them they've been logged out (somehow)
            }
        });
    }

    ngOnDestroy() {
        if (this.sub != null) {
            this.sub.unsubscribe();
        }
    }
}

This makes use of an Authentication service I wrote to determine whether or not the user is already logged in and also subscribes to the authentication event so that it can kick a user out if he or she logs out or times out.

You could do the same thing. You'd create a directive like mine that checks for the presence of a necessary cookie or other state information that indicates that the user is authenticated. If they don't have those flags you are looking for, redirect the user to your main public page (like I do) or your OAuth2 server (or whatever). You would put that directive attribute on any component that needs to be protected. In this case, it might be called protected like in the directive I pasted above.

<members-only-info [protected]></members-only-info>

Then you would want to navigate/redirect the user to a login view within your app, and handle the authentication there. You'd have to change the current route to the one you wanted to do that. So in that case you'd use dependency injection to get a Router object in your directive's constructor() function and then use the navigate() method to send the user to your login page (as in my example above).

This assumes that you have a series of routes somewhere controlling a <router-outlet> tag that looks something like this, perhaps:

@RouteConfig([
    {path: '/loggedout', name: 'LoggedoutPage', component: LoggedoutPageComponent, useAsDefault: true},
    {path: '/public', name: 'PublicPage', component: PublicPageComponent},
    {path: '/protected', name: 'ProtectedPage', component: ProtectedPageComponent}
])

If, instead, you needed to redirect the user to an external URL, such as your OAuth2 server, then you would have your directive do something like the following:

window.location.href="https://myserver.com/oauth2/authorize?redirect_uri=http://myAppServer.com/myAngular2App/callback&response_type=code&client_id=clientId&scope=my_scope

这篇关于Angular2重定向到登录页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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