kir-dev / passport-authsch

passport.js strategy for AuthSCH

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

passport-authsch

This package is a strategy for passport.js and AuthSCH, and a few other things that we use in our NestJs applications related to authentication.

Usage

To set up JWT authtentication with AuthSCH in a Nest.js application, follow these steps:

Install packages

Install the following packages:

yarn add passport @nestjs/passport @kir-dev/passport-authsch passport-jwt @nestjs/jwt

Create auth resource

Create an auth module, controller and service

nest g module auth
nest g controller auth
nest g service auth

Create an AuthSch Strategy

This package exports a Strategy that you can use with passport.js and NestJS. To do this, you need to create a class that extends the exported Strategy using @nestjs/passport's wrapper.

Create a file called authsch.strategy.ts in the auth directory.

import { AuthSchProfile, AuthSchScope, Strategy } from '@kir-dev/passport-authsch';
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';

@Injectable()
export class AuthSchStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      clientId: '<your authSch clientId>',
      clientSecret: '<your authSch clientSecret',
      scopes: [AuthSchScope.PROFILE, ...],
    });
  }

  async validate(userProfile: AuthSchProfile): Promise<any> {
    <<custom logic ...>>
  }
}

To use AuthSCH, we must provide a clientId, clientSecret and a list of scopes to the base class. You can generate an id and secret at AuthSCH's website. The description of the scopes can be read in the passage about AuthSchScopes.

The validate method will be called after the user decides to share their data and that data is retrieved from AuthSCH. The data is parsed by this library and passed as a parameter in the form of a AuthSchProfile object, read more in the same passage. The validate method can be used for validating the user's data. You can create custom logic here, we usually check if they're already in our database, and if not, we insert them. If you return undefined or null from this method, the authentication will fail. If you return anything else, that value will be availabe on req.user on every subsequent request where the @UseGuards(AuthGuard('authsch')) decorator is present.

Create a JWT strategy

AuthSCH is used for authenticating the user on their first login, but on subsequent logins we'll use JWTs. The passport-jwt library handles this, but once again we have to create a class to implement their logic.

Create a file called jwt.strategy.ts in the auth directory.

import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { User } from 'src/users/entities/user.entity';
import { ExtractJwt, Strategy } from 'passport-jwt';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: '<your JWT secret>',
    });
  }

  validate(payload: User): User {
    return payload;
  }
}

Provide a secret in the constructor, change the other settings to your liking. No real validation needed in the validate method.

Edit the Auth Module

import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';

import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { JwtStrategy } from './jwt.strategy';
import { AuthSchStrategy } from './authsch.strategy';

@Module({
  providers: [AuthService, AuthSchStrategy, JwtStrategy],
  controllers: [AuthController],
  imports: [PassportModule, JwtModule],
})
export class AuthModule {}

Edit the Auth Service

import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { User } from 'src/users/entities/user.entity';

@Injectable()
export class AuthService {
  constructor(private jwtService: JwtService) {}

  login(user: User): string {
    return this.jwtService.sign(user, {
      secret: '<your secret>',
      expiresIn: '7 days',
    });
  }
}

The login method will create a JWT token with the users data. Feel free to use custom logic here, also modify the the secret and expiration of the token.

Edit the Auth Controller

import { CurrentUser } from '@kir-dev/passport-authsch';
import { Controller, Get, Redirect, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { User } from 'src/users/entities/user.entity';

import { AuthService } from './auth.service';

@Controller('auth')
export class AuthController {
  constructor(private authService: AuthService) {}
  /**
   * Redirects to the authsch login page
   */
  @UseGuards(AuthGuard('authsch'))
  @Get('login')
  login() {
    // never called
  }

  /**
   * Endpoint for authsch to call after login
   * Redirects to the frontend with the jwt token
   */
  @Get('callback')
  @UseGuards(AuthGuard('authsch'))
  @Redirect()
  oauthRedirect(@CurrentUser() user: User) {
    const jwt = this.authService.login(user);
    return {
      url: `<your_frontend_url>?jwt=${jwt}`,
    };
  }
}

On your frontend, when the user clicks the login button, that should lead to to <your_backend_url>/auth/login. The AuthSch guard will redirect the user to the AuthSch login page and the body of this method will never be called.

When registering your AuthSch client, for the redirectUrl you should provide <your_backend_url>/auth/redirect. When the user signs in through AuthSch, it will call this endpoint. This strategy will retrieve the accessToken and the userData, run the validate method in authsch.strategy.ts and then call this method. The result of the validate method will be on the req.user, which the @CurrentUser() decorator extracts (more on that here). Then the JWT is generated and sent back to the frontend.

Final steps

And with that, you're done! To enforce authentication on endpoints or controllers, add the @UseGuards(AuthGuard('jwt)) decorator to the method or class. (If you're using Swagger, also add the @ApiBearerAuth()). If that endpoint is called without a JWT in the Authorization header, a 401 Unauthorized error will be returned. You can extract the user data with the @CurrentUser() decorator in the controller method parameters.

Example endpoint using the JWT authentication

@UseGuards(AuthGuard('jwt'))
@ApiBearerAuth()
@Get(':id')
async findOne(
  @Param('id', ParseIntPipe) id: number,
  @CurrentUser() user: UserEntity,
): Promise<...> {
  ...
}

Example PR that implements authentication with this library in a NestJS app (though with v1, the enums and types changed a bit in v2)

Documentation

AuthSchScope and AuthSchProfile

The available scopes of AuthSCH can be found here. The AuthSchScope is an enum that maps to these scopes. The validate method will get an object with type AuthSchProfile as parameter, which is not the same that AuthSch returns and their documentation describes. Here you can read the mapping in the following format: enum name - scope name - property (or properties) in AuthSchProfile. NOTE: Only those properties will be on the object in the validate method whose scope was provided in the constructor. The other fields will be undefined, but the type can't reflect that!

  • PROFILE - profile - fullName, firstName, lastName, birthDate
  • EMAIL - email - email, emailVerified
  • PHONE - phone - phone, phoneVerified
  • ADDRESS - address - address
  • NEPTUN - bme.hu:niifPersonOrgID - neptun
  • ROLES - roles - schAcc.roles (array of string values)
  • EDU_ID - bme.hu:eduPersonPrincipalName - bme.eduId (XY@bme.hu)
  • ATTENDED_COURSES - bme.hu:niifPersonAttendedCourse - bme.attendedCourses (array of course codes)
  • BME_STATUS - meta.bme.hu:unitScope - bme.bmeStatus (array of BmeUnitScope enum values)
  • SCH_GROUPS - directory.sch.bme.hu:groups - schAcc.groups
  • SCHACC_ID - directory.sch.bme.hu:sAMAccountName - schAcc.schAccUsername
  • PEK_PROFILE - pek.sch.bme.hu:profile - pek.executiveAt, pek.activeMemberAt, pek.alumniMemberAt, pek.pekId, entrants (array of objects with the following keys: groupId, groupName, entrantType ('AB' or 'KB'))

The openid and offline_access scopes are not available through this package. The openid scope is required for the current version of AuthSCH to work, so that scope will be added by the package by default. The offline_scope is needed for refresh tokens, but this library currently doesn't support that.

CurrentUser decorator

This package also exports two NestJs decorators, CurrentUser and CurrentUserOptional. CurrentUser extracts the user property from the current request object. If there's no user property, it throws an InternalServerError exception. This usually happens when you used this decorator on an endpoint where the JWT or AuthSch guard wasn't used, and thus the user info wasn't available. The CurrentUserOptional does the same thing, but it doesn't throw an error if there's no user data, it just returns undefined. This can be beneficial on endpoints when authentication is optional.

About

passport.js strategy for AuthSCH


Languages

Language:TypeScript 87.1%Language:JavaScript 12.9%