繁体   English   中英

如何防止用户登录后返回登录页面

[英]How to prevent the user from going back to login page after logged in

在我的 angular 应用程序中,我登录了 function。这是我的 authservice.service.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';


@Injectable({
   providedIn: 'root'
})
export class AuthserviceService {

  constructor(private http:HttpClient) { }
    login(data):Observable<any>{
    console.log("I am server");
    return this.http.post('http://localhost:8000/api/login/',data);
  }
}

这是我的 loginComponent.ts

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthserviceService } from 'src/app/authservice.service';
import { HttpErrorResponse } from '@angular/common/http';



@Component({
  selector: 'sl8-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
   })
   export class LoginComponent implements OnInit {
   formGroup : FormGroup;
   constructor(private authService :AuthserviceService, private _router : Router) { }

  ngOnInit(): void {
    this.initForm();
  }
  initForm(){
    this.formGroup =new FormGroup({
     email : new FormControl('',[Validators.required]),
      password : new FormControl('',[Validators.required]),
    })
  }


  loginProcess(){
    if(this.formGroup.valid){      
       this.authService.login(this.formGroup.value).subscribe(results => {
          this._router.navigate(['/home'])
       }, (error: HttpErrorResponse) => {
           const message = error.error.detail;
          console.log(message);
          if (error.status === 400)
            alert('Invalid form inputs')
          else if (error.status === 401)
             alert('Invalid Credentials Provided')
       });
    } 
  }

}

以下是我输入正确凭据时的 postman 结果。

"email": "test@gmail.com", "tokens": "{'refresh': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTYxMzAxNTI5NSwianRpIjoiMzliNzY0N2ExMjVhNDI2M2E2MTVlYjhiZmQ4ZTgyYzgiLCJlbWFpbCI6InRlc3RAZ21haWwuY29tIn0.-mEy9rWyRm7lXsnG-JfoGFgn4GrLrOa-hAkBm0gyb8s', 'access': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjExODE3Njk1LCJqdGkiOiIwMTExNmU2NWI0OTM0YTcwYmJiNGM2ZjhkZDEyZTU4YSIsImVtYWlsIjoidGVzdEBnbWFpbC5jb20ifQ.Raf38'}" }

登录 function 工作正常。 但问题是当我登录时我会重定向到主页。 但是如果我点击后退按钮它再次 go 到登录页面。 我该如何防止这种情况。

创建一个Guard并使用canActivate ,它会在用户已经登录的情况下每当访问/login时重定向到/home

登录卫士:

export class LoginGuard implements CanActivate {
    canActivate(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): boolean {
        // redirect logic goes here
    }
}

在您的路由器配置中:

{
    path: '/login',
    component: LoginComponent,
    canActivate: [LoginGuard],
}

您应该使用路径 '' 和 canActivate 属性创建一个路由文件

每次将身份验证令牌传递给登录页面,如果令牌不为空则重定向。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM