-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
8d404cc
commit cef470b
Showing
8 changed files
with
300 additions
and
64 deletions.
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,24 +1,35 @@ | ||
import { Controller, Post } from '@nestjs/common'; | ||
import { Controller, Get, Res, Session, UseGuards } from '@nestjs/common'; | ||
import { ApiAcceptedResponse, ApiTags } from '@nestjs/swagger'; | ||
import { AuthenticatedUser, Public, Resource } from 'nest-keycloak-connect'; | ||
import { Response } from 'express'; | ||
import { LoginGuard } from '../login.guard.js'; | ||
|
||
@ApiTags('frontend') | ||
@Controller({ path: 'frontend' }) | ||
export class FrontendController { | ||
// Endpoints decorated with @Public are accessible to everyone | ||
@Public() | ||
@Resource('test') | ||
@Post('login') | ||
@UseGuards(LoginGuard) | ||
@Get('login') | ||
@ApiAcceptedResponse({ description: 'The person was successfully logged in.' }) | ||
public login(): string { | ||
return 'Login!'; | ||
} | ||
|
||
// Endpoints without @Public decorator automatically verify user | ||
@Post('logout') | ||
@Get('logout') | ||
@ApiAcceptedResponse({ description: 'The person was successfully logged out.' }) | ||
public logout(@AuthenticatedUser() user: unknown): string { | ||
public logout(): string { | ||
// Can get logged in user with @AuthenticatedUser (technically any-type, is the JSON response from keycloak) | ||
return `Logout! ${JSON.stringify(user)}`; | ||
return 'Logout!'; | ||
} | ||
|
||
@Get('callback') | ||
@UseGuards(LoginGuard) | ||
public callback(@Res() response: Response): void { | ||
response.redirect('/api/frontend/loginInfo'); | ||
} | ||
|
||
@Get('loginInfo') | ||
public loginInfo(@Session() session: { passport: object }): string { | ||
return JSON.stringify(session.passport) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,9 +1,28 @@ | ||
import { Module } from '@nestjs/common'; | ||
import { FrontendController } from './api/frontend.controller.js'; | ||
import { OpenidStrategy } from './openid.strategy.js'; | ||
import { Issuer } from 'openid-client'; | ||
import { PassportModule } from '@nestjs/passport'; | ||
import {SessionSerializer} from "./session.serializer.js"; | ||
|
||
@Module({ | ||
imports: [], | ||
providers: [], | ||
imports: [PassportModule.register({ session: true, defaultStrategy: 'openid' })], | ||
providers: [ | ||
{ | ||
provide: OpenidStrategy, | ||
useFactory: async (): Promise<OpenidStrategy> => { | ||
const TrustIssuer = await Issuer.discover( | ||
'https://keycloak.dev.spsh.dbildungsplattform.de/realms/master', | ||
); | ||
const client = new TrustIssuer.Client({ | ||
client_id: 'spsh', | ||
client_secret: 'YDp6fYkbUcj4ZkyAOnbAHGQ9O72htc5M', | ||
}); | ||
return new OpenidStrategy(client); | ||
}, | ||
}, | ||
SessionSerializer | ||
], | ||
controllers: [FrontendController], | ||
}) | ||
export class FrontendApiModule {} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
import { ExecutionContext, Injectable } from '@nestjs/common'; | ||
import { AuthGuard } from '@nestjs/passport'; | ||
|
||
@Injectable() | ||
export class LoginGuard extends AuthGuard('openid') { | ||
public override async canActivate(context: ExecutionContext): Promise<boolean> { | ||
const result = (await super.canActivate(context)) as boolean; | ||
await super.logIn(context.switchToHttp().getRequest()); | ||
return result; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
import { PassportStrategy } from '@nestjs/passport'; | ||
import { AuthorizationParameters, Client, Strategy, StrategyOptions, TokenSet, UserinfoResponse } from 'openid-client'; | ||
import { UnauthorizedException } from '@nestjs/common'; | ||
|
||
export class OpenidStrategy extends PassportStrategy(Strategy, 'openid') { | ||
public constructor(private client: Client) { | ||
super({ | ||
client: client, | ||
usePKCE: true, | ||
params: { redirect_uri: 'http://127.0.0.1:9091/api/frontend/callback' }, | ||
} as StrategyOptions); | ||
} | ||
|
||
public async validate(tokenset: TokenSet): Promise<AuthorizationParameters> { | ||
const userinfo: UserinfoResponse = await this.client.userinfo(tokenset); | ||
|
||
try { | ||
const idToken = tokenset.id_token; | ||
const accessToken = tokenset.access_token; | ||
const refreshToken = tokenset.refresh_token; | ||
const user = { | ||
id_token: idToken, | ||
access_token: accessToken, | ||
refresh_token: refreshToken, | ||
userinfo, | ||
}; | ||
return user; | ||
} catch (err) { | ||
throw new UnauthorizedException(); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
import { PassportSerializer } from '@nestjs/passport'; | ||
import { Injectable } from '@nestjs/common'; | ||
|
||
@Injectable() | ||
export class SessionSerializer extends PassportSerializer { | ||
public serializeUser(user: unknown, done: (err: Error | null, user: unknown) => void): void { | ||
done(null, user); | ||
} | ||
|
||
public deserializeUser(payload: string, done: (err: Error | null, payload: string) => void): void { | ||
done(null, payload); | ||
} | ||
} |