Thursday 26 November 2020

Custom login page with OKTA and Angular 10

I'm having some issues here where is not logging me in. Nothing on the console either. Here is the form in the login.component.html

<form [formGroup]="form"  (ngSubmit)="onSubmit()">
  <p *ngIf="loginInvalid" class="text-danger">
     The username and password were not recognized
  </p>
          
  <div class="form-group">
     <label for="username">Username</label>
     <input type="email" class="form-control" id="username">
  </div>
  <div class="form-group">
     <label for="exampleInputPassword1">Password</label>
     <input type="password" class="form-control" id="exampleInputPassword1" required>
  </div>
  <div class="form-group form-check">
     <input type="checkbox" class="form-check-input" id="rememerPass">
     <label class="form-check-label" for="rememerPass">Remember Password</label>
  </div>
  <button type="submit" class="btn btn-primary w-100 mt-4 mb-3">Login</button>
  <button type="button" class="btn btn-secondary w-100 mb-2">Register</button>
  <button type="button" class="btn btn-link w-100">Forgot Password</button>
</form>

the login.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { AuthService } from '../../auth.service';

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

export class LoginComponent implements OnInit {
  form: FormGroup;
  public loginInvalid: boolean;
  private formSubmitAttempt: boolean;
  private returnUrl: string;

  constructor(
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private authService: AuthService
  ) {
 }

  async ngOnInit() {
    this.returnUrl = this.route.snapshot.queryParams.returnUrl || '/dashboard';

    this.form = this.fb.group({
      username: ['', Validators.email],
      password: ['', Validators.required]
    });

    if (await this.authService.checkAuthenticated()) {
      await this.router.navigate([this.returnUrl]);
    }
  }

  async onSubmit() {
    console.log("event fired");

    this.loginInvalid = false;
    this.formSubmitAttempt = false;
    if (this.form.valid) {
      try {
        const username = this.form.get('username').value;
        const password = this.form.get('password').value;
        await this.authService.login(username, password);
        console.log("username: ",username, "password: ", password);
    
      } catch (err) {
        this.loginInvalid = true;
      }
    } else {
      this.formSubmitAttempt = true;
    }
  }
}

and the auth.service.ts

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { OktaAuth } from '@okta/okta-auth-js';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class AuthService {
  private authClient = new OktaAuth({
    issuer:"https://dev-#######.okta.com/oauth2/default",
    clientId:"##########################",
  });

  public isAuthenticated = new BehaviorSubject<boolean>(false);

  constructor(private router: Router) {
  }

  async checkAuthenticated() {
    const authenticated = await this.authClient.session.exists();
    this.isAuthenticated.next(authenticated);
    return authenticated;
  }

  async login(username: string, password: string) {
    const transaction = await this.authClient.signIn({username, password});

    if (transaction.status !== 'SUCCESS') {
      throw Error('We cannot handle the ' + transaction.status + ' status');
    }
    this.isAuthenticated.next(true);

    this.authClient.session.setCookieAndRedirect(transaction.sessionToken);
  }

  async logout(redirect: string) {
    try {
      await this.authClient.signOut();
      this.isAuthenticated.next(false);
      this.router.navigate([redirect]);
    } catch (err) {
      console.error(err);
    }
  }
}

Nothing happens, although the logout does work (implemented in the navbar {not shown} )

What am I missing? What else do you need to see?



from Custom login page with OKTA and Angular 10

No comments:

Post a Comment