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

时间:2021-01-28 11:03:04

标签: angular authentication

在我的 angular 应用程序中,我有登录功能。 这是我的 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')
       });
    } 
  }

}

以下是我输入正确凭据后的邮递员结果。

<块引用>

“电子邮件”: “test@gmail.com”, “标记”:“{ '刷新': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTYxMzAxNTI5NSwianRpIjoiMzliNzY0N2ExMjVhNDI2M2E2MTVlYjhiZmQ4ZTgyYzgiLCJlbWFpbCI6InRlc3RAZ21haWwuY29tIn0.-mEy9rWyRm7lXsnG-JfoGFgn4GrLrOa-hAkBm0gyb8s', '接入': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjExODE3Njk1LCJqdGkiOiIwMTExNmU2NWI0OTM0YTcwYmJiNGM2ZjhkZDEyZTU4YSIsImVtYWlsIjoidGVzdEBnbWFpbC5jb20ifQ.Raf38'} " }

登录功能工作正常。但问题是当我登录时,我会重定向到主页。但是如果我点击后退按钮它再次进入登录页面。我怎样才能防止这种情况发生。

3 个答案:

答案 0 :(得分:0)

创建一个 Guard 并利用 canActivate 重定向到 /home 每当 /login 被访问而用户在已经登录。

登录卫士:

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

在您的路由器配置中:

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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