Roger Sánchez
Roger Sánchez

Reputation: 87

Keycloak authorization in Angular

I stuck in setting up a authorization.

I downloaded keycloak-3-2-1.Final and set up a new realm.

{
  "realm": "proteomics",
  "auth-server-url": "http://localhost:8080/auth",
  "ssl-required": "external",
  "resource": "account",
  "credentials": {
    "secret": "696caa69-9259-45f5-a264-0d9da083f933"
  },
  "use-resource-role-mappings": true
}

Then I started a new angular project with 'ng new'. In this project I added keycloak-js npm install --save keyclak-js

My problem now is, how do I connect all these things together. On my header.component.html I want a single button to login (authenticate). Can anyone explain where and how I have to import keycloak-js and if anything else is missing, give me a hint to finish a simple login page?

app.compnent.ts

import { Component } from '@angular/core';
import { HeaderComponent } from './header/header.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
}

app.component.html

<app-header></app-header>

header.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }
}

header.component.html

<nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="navbar-header">
      <a href="#" class="navbar-brand">ProtSkive</a>
    </div>
    <div class="navbar-collapse">
       <ul class="nav navbar-nav navbar-right">
         <button class="btn navbar-btn" id="login">Login</button> 
       </ul>    
    </div>
  </div>
</nav>

Upvotes: 3

Views: 958

Answers (2)

linusum
linusum

Reputation: 106

You can use the Keycloak UI if you implement the KeycloakService

import {KeycloakService} from "keycloak-angular";

export class AuthService {

    public isLoggedIn = false

    constructor(private readonly keycloak: KeycloakService) { }

    public login() {
    this.keycloak.login();
    }

}

Using the login() method on your button will redirect the user to the specified keycloak realm. If you´ve set up the realm correctly, the user will be redirected to your application after a successfull authentification.

Follow the exact instructions for the keycloak-angular setup and the example project

Upvotes: 0

Alisher
Alisher

Reputation: 940

As far as I know, Kecloak is a standalone server meaning it is independent of your angular app. If you would like to have nav-bar in Keycloak you will have to change login page themes settings. Alternatively, you could implement login through REST and build your custom login page.

Upvotes: 1

Related Questions