1
resposta

Redirecionamento não funciona após o token

Boa tarde. Após a implementação do token JWT, percebo que o redirecionamento não funciona mais, mas sim retorna para a pagina 404.

Devo liberar alguma ação?

Login Component

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';


import {Router} from '@angular/router';



import { AutenticacaoService } from 'src/app/autenticacao/autenticacao.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})

/**
 * Login component
 */
export class LoginComponent implements OnInit {

  //loginForm: FormGroup;
  submitted = false;
  error = '';
  returnUrl: string;

  usuario = '';
  senha = '';

  // set the currenr year
  year: number = new Date().getFullYear();

  // tslint:disable-next-line: max-line-length
  constructor(private formBuilder: FormBuilder, private router: Router,
    private authService:AutenticacaoService) { }

  ngOnInit() {
  }

  // convenience getter for easy access to form fields
 // get f() { return this.loginForm.controls; }

  /**
   * Form submit
   */
  onSubmit(): void{

  }
  login(){
    this.authService.autenticar(this.usuario,this.senha).subscribe(()=>{
     this.router.navigate(['/dashboard']);
    },(error)=>{
      console.log(error);
      alert("Usuário ou senha invalidos");

    });
  }
}


Autenticacao Service

import { HttpClient, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { UsuarioService } from './usuario/usuario.service';

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

  constructor(private httpClient : HttpClient , private usuarioService:UsuarioService) { }

  autenticar(usuario:string, senha:string): Observable<HttpResponse<any>>{
    return this.httpClient.post('http://localhost/find-records/account/auth',{
      user: usuario,
      password: senha
    },
    {observe:'response' }
    ).pipe(
      tap((res)=> {

        const authToken = res.headers.get("X-Access-Token") ?? '';
       this.usuarioService.salvaToken(authToken);
      })
    )
  }
}

App-Routing

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { AuthGuard } from './core/guards/auth.guard';
import { LayoutComponent } from './layouts/layout.component';
import { CyptolandingComponent } from './cyptolanding/cyptolanding.component';
import { Page404Component } from './extrapages/page404/page404.component';

const routes: Routes = [
  { path: 'account', loadChildren: () => import('./account/account.module').then(m => m.AccountModule) },
  {path: '', pathMatch: 'full', redirectTo: 'account/login'},
  { path: '', component: LayoutComponent, loadChildren: () => import('./pages/pages.module').then(m => m.PagesModule), canActivate: [AuthGuard] },
  { path: 'pages', loadChildren: () => import('./extrapages/extrapages.module').then(m => m.ExtrapagesModule), canActivate: [AuthGuard] },
  { path: 'crypto-ico-landing', component: CyptolandingComponent },
  { path: '**', component: Page404Component },

];

@NgModule({
  imports: [RouterModule.forRoot(routes, { scrollPositionRestoration: 'top', relativeLinkResolution: 'legacy' })],
  exports: [RouterModule]
})

export class AppRoutingModule { }
1 resposta

Eu também estou com esse mesmo problema. Após realizar o serviço de autenticação o quando clico em login ele não loga. Dá usuário ou senha inválidos.