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

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

问题描述

我来自 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 中处理用户授权的最佳实践是什么?

推荐答案

更新:我已经发布了一个完整的骨架 Github 上的 Angular 2 项目与 OAuth2 集成,显示了下面提到的指令在行动中.

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

一种方法是使用指令.与 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天全站免登陆