【问题标题】:Angular 2 JWT have unauthenticatedRedirector?Angular 2 JWT 有未经身份验证的重定向器?
【发布时间】:2017-08-27 02:10:59
【问题描述】:

我来自 angular 1,我使用 JWT 令牌对用户进行身份验证。在角度 1 中,我有这个:

.config(function Config($httpProvider, jwtOptionsProvider) {
        // Interceptor for token push on every $http request
        jwtOptionsProvider.config({
            tokenGetter: ['storageService', function (storageService) {
                return storageService.getToken();
            }],
            whiteListedDomains: ['127.0.0.1', 'localhost'],
            unauthenticatedRedirector: ['$state', 'authManager', 'storageService', 'jwtHelper', function ($state, authManager, storageService, jwtHelper) {
                if (storageService.getToken() != null) {
                    if (jwtHelper.isTokenExpired(storageService.getToken())) {
                        alert('Su sesión ha caducado.');
                    }
                }

                storageService.removeToken();
                storageService.clearAll();
                authManager.unauthenticate();
                $state.go('autorepuestos_fe');
            }],
            unauthenticatedRedirectPath: '/login'
        });

        $httpProvider.interceptors.push('jwtInterceptor');
    })

这是拦截器。我通过 JWT for Angular 2 的官方页面了解到,我可以轻松拦截用户的路由并使用 AuthGuard 将其重定向。没关系,我用过并且效果很好。但是,我的问题是……在这个版本的 Angular 2 JWT 上是否有 unauthenticatedRedirector?有了这个,如果用户向我后端的任何端点发出请求,那么会自动显示一条消息并将其重定向到登录页面。

知道如何实现这一点吗?我正在考虑放置一个函数来拦截对任何端点的每次调用并首先验证令牌是否有效,如果这是真的然后发出请求......但听起来很复杂。

【问题讨论】:

    标签: angular authentication jwt angular2-jwt


    【解决方案1】:

    在 Angular 2 和 4 中重定向登录可以通过路由中的“canActivate”来完成,如果需要,可以添加一些消息

    这是我的 AuthGuard 路由设置

    { path: 'secret', component: SecretComponent, canActivate: [ AuthService] }
    

    然后在我的 AuthGuard 中

    public canActivate() {
        if (this.checkLogin()) {
            return true;
        } else {
            this.router.navigate(['login']);
            return false;
        }
    }
    

    向您展示 ASP.NET Angular JWT 解决方案的完整详细信息:

    https://github.com/Longfld/ASPNETcoreAngularJWT

    【讨论】:

      【解决方案2】:

      ng-jwt库,在angular +2中提供一些jwt认证工具

      【讨论】:

        猜你喜欢
        • 2017-06-06
        • 2016-09-25
        • 2021-07-17
        • 2016-11-15
        • 2020-02-22
        • 2019-03-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多