角度重定向到登录页面 [英] Angular redirect to login page

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

问题描述

我来自Asp.Net MVC世界,在该世界中,试图访问未经授权的页面的用户会自动重定向到登录页面.

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.

我正在尝试在Angular上重现此行为.我遇到了@CanActivate装饰器,但是它导致该组件完全不呈现,也没有重定向.

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

我的问题如下:

  • Angular是否提供一种实现此行为的方法?
  • 如果是这样,怎么办?这是一个好习惯吗?
  • 如果没有,在Angular中处理用户授权的最佳实践是什么?

推荐答案

更新:我已经发布了完整的骨架

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

一种方法是使用directive.与Angular 2 components基本不同,Angular 2 components基本上是您插入到页面中的新HTML标记(具有关联的代码),归因指令是您放入标记中的属性,该属性会导致某些行为. 此处的文档.

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.

自定义属性的存在会导致放置指令的组件(或HTML元素)发生问题.考虑一下我在当前Angular2/OAuth2应用程序中使用的指令:

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.

您可以做同样的事情.您将创建一个类似我的指令,以检查是否存在必要的cookie或其他状态信息,该信息指示用户已通过身份验证.如果它们没有您要查找的标志,则将用户重定向到您的主要公共页面(如我)或您的OAuth2服务器(或其他).您可以将该指令属性放在需要保护的任何组件上.在这种情况下,它可能像我上面粘贴的指令一样被称为protected.

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>

然后,您想要将用户导航/重定向到应用程序中的登录视图,并在那里进行身份验证.您必须将当前路线更改为您要执行的路线.因此,在这种情况下,您将使用依赖项注入在其中获取 Router对象您指令的constructor()函数,然后使用navigate()方法将用户发送到您的登录页面(如上述示例所示).

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

这假设您在某处控制着<router-outlet>标签的一系列路线,该标签看起来像这样:

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}
])

相反,如果您需要将用户重定向到外部 URL(例如OAuth2服务器),则您的指令将执行以下操作:

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

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

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