- 
                Notifications
    You must be signed in to change notification settings 
- Fork 167
feat: add generic oidc provider #25
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Open
      
      
            maximilianmikus
  wants to merge
  18
  commits into
  atinux:main
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
maximilianmikus:oidc
  
      
      
   
  
    
  
  
  
 
  
      
    base: main
Could not load branches
            
              
  
    Branch not found: {{ refName }}
  
            
                
      Loading
              
            Could not load tags
            
            
              Nothing to show
            
              
  
            
                
      Loading
              
            Are you sure you want to change the base?
            Some commits from the old base branch may be removed from the timeline,
            and old review comments may become outdated.
          
          
  
     Open
                    Changes from all commits
      Commits
    
    
            Show all changes
          
          
            18 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      e9e31da
              
                feat: added simple pkce and state checks for auth0
              
              
                Azurency bc64538
              
                refactor: moved checks to a separate security util, replaced crypto b…
              
              
                Azurency 29f3106
              
                Merge branch 'main' of https://github.com/Atinux/nuxt-auth-utils
              
              
                Azurency 915eef6
              
                fix: updated cookies to use SameSite=Lax
              
              
                Azurency 7113f98
              
                Merge branch 'main' of https://github.com/Atinux/nuxt-auth-utils
              
              
                Azurency abf4754
              
                Merge branch 'main' of https://github.com/Atinux/nuxt-auth-utils
              
              
                Azurency 5405e60
              
                chore: removed extra console.log
              
              
                Azurency c6f2c2d
              
                fix: removed Auth0 mentions in security util
              
              
                Azurency ff45896
              
                feat: added cookie settings for the security util
              
              
                Azurency 119ca71
              
                fix: add missing imports
              
              
                Azurency 6cd7498
              
                Merge branch 'main' of https://github.com/Atinux/nuxt-auth-utils
              
              
                Azurency ac80fc4
              
                feat: add generic oidc provider.
              
              
                maximilianmikus 6f3a81d
              
                fix: integrate security utils.
              
              
                maximilianmikus 4d0b413
              
                fix: default config variable name.
              
              
                maximilianmikus f4b2659
              
                feat: add config validation util.
              
              
                maximilianmikus d4b211d
              
                fix: improve doc comment.
              
              
                maximilianmikus d85568e
              
                fix: update readme.
              
              
                maximilianmikus ed1ffb5
              
                Merge branch 'main' into oidc
              
              
                maximilianmikus File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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,172 @@ | ||
| import type { H3Event, H3Error } from 'h3' | ||
| import { eventHandler, createError, getQuery, sendRedirect } from 'h3' | ||
| import { withQuery } from 'ufo' | ||
| import { ofetch } from 'ofetch' | ||
| import { defu } from 'defu' | ||
| import { useRuntimeConfig } from '#imports' | ||
| import type { OAuthConfig } from '#auth-utils' | ||
| import { type OAuthChecks, checks } from '../../utils/security' | ||
| import { validateConfig } from '../../utils/config' | ||
|  | ||
| export interface OAuthOidcConfig { | ||
| /** | ||
| * OIDC Client ID | ||
| * @default process.env.NUXT_OAUTH_OIDC_CLIENT_ID | ||
| */ | ||
| clientId?: string | ||
| /** | ||
| * OIDC Client Secret | ||
| * @default process.env.NUXT_OAUTH_OIDC_CLIENT_SECRET | ||
| */ | ||
| clientSecret?: string | ||
| /** | ||
| * OIDC Response Type | ||
| * @default process.env.NUXT_OAUTH_OIDC_RESPONSE_TYPE | ||
| */ | ||
| responseType?: string | ||
| /** | ||
| * OIDC Authorization Endpoint URL | ||
| * @default process.env.NUXT_OAUTH_OIDC_AUTHORIZATION_URL | ||
| */ | ||
| authorizationUrl?: string | ||
| /** | ||
| * OIDC Token Endpoint URL | ||
| * @default process.env.NUXT_OAUTH_OIDC_TOKEN_URL | ||
| */ | ||
| tokenUrl?: string | ||
| /** | ||
| * OIDC Userino Endpoint URL | ||
| * @default process.env.NUXT_OAUTH_OIDC_USERINFO_URL | ||
| */ | ||
| userinfoUrl?: string | ||
| /** | ||
| * OIDC Redirect URI | ||
| * @default process.env.NUXT_OAUTH_OIDC_USERINFO_URL | ||
| */ | ||
| redirectUri?: string | ||
| /** | ||
| * OIDC Code challenge method | ||
| * @default process.env.NUXT_OAUTH_OIDC_CODE_CHALLENGE_METHOD | ||
| */ | ||
| codeChallengeMethod?: string | ||
| /** | ||
| * OIDC Grant Type | ||
| * @default process.env.NUXT_OAUTH_OIDC_GRANT_TYPE | ||
| */ | ||
| grantType?: string | ||
| /** | ||
| * OIDC Claims | ||
| * @default process.env.NUXT_OAUTH_OIDC_AUDIENCE | ||
| */ | ||
| audience?: string | ||
| /** | ||
| * OIDC Claims | ||
| * @default {} | ||
| */ | ||
| claims?: {} | ||
| /** | ||
| * OIDC Scope | ||
| * @default [] | ||
| * @example ['openid'] | ||
| */ | ||
| scope?: string[] | ||
| /** | ||
| * A list of checks to add to the OIDC Flow (eg. 'state' or 'pkce') | ||
| * @default [] | ||
| * @see https://auth0.com/docs/flows/authorization-code-flow-with-proof-key-for-code-exchange-pkce | ||
| * @see https://auth0.com/docs/protocols/oauth2/oauth-state | ||
| */ | ||
| checks?: OAuthChecks[] | ||
| } | ||
|  | ||
| export function oidcEventHandler({ config, onSuccess, onError }: OAuthConfig<OAuthOidcConfig>) { | ||
| return eventHandler(async (event: H3Event) => { | ||
| // @ts-ignore | ||
| config = defu(config, useRuntimeConfig(event).oauth?.oidc) as OAuthOidcConfig | ||
| const { code } = getQuery(event) | ||
|  | ||
| const validationResult = validateConfig(config, ['clientId', 'clientSecret', 'authorizationUrl', 'tokenUrl', 'userinfoUrl', 'redirectUri', 'responseType']) | ||
|  | ||
| if (!validationResult.valid && validationResult.error) { | ||
| if (!onError) throw validationResult.error | ||
| return onError(event, validationResult.error) | ||
| } | ||
|  | ||
| if (!code) { | ||
| const authParams = await checks.create(event, config.checks) // Initialize checks | ||
| // Redirect to OIDC login page | ||
| return sendRedirect( | ||
| event, | ||
| withQuery(config.authorizationUrl as string, { | ||
| response_type: config.responseType, | ||
| client_id: config.clientId, | ||
| redirect_uri: config.redirectUri, | ||
| scope: config?.scope?.join(' ') || 'openid', | ||
| claims: config?.claims || {}, | ||
| grant_type: config.grantType || 'authorization_code', | ||
| audience: config.audience || null, | ||
| ...authParams | ||
| }) | ||
| ) | ||
| } | ||
|  | ||
| // Verify checks | ||
| let checkResult | ||
| try { | ||
| checkResult = await checks.use(event, config.checks) | ||
| } catch (error) { | ||
| if (!onError) throw error | ||
| return onError(event, error as H3Error) | ||
| } | ||
|  | ||
| // @ts-ignore | ||
| const queryString = new URLSearchParams({ | ||
| code, | ||
| client_id: config.clientId, | ||
| client_secret: config.clientSecret, | ||
| redirect_uri: config.redirectUri, | ||
| response_type: config.responseType, | ||
| grant_type: config.grantType || 'authorization_code', | ||
| ...checkResult | ||
| }) | ||
|  | ||
| // Request tokens. | ||
| const tokens: any = await ofetch( | ||
| config.tokenUrl as string, | ||
| { | ||
| method: 'POST', | ||
| headers: { | ||
| 'Content-Type': 'application/x-www-form-urlencoded' | ||
| }, | ||
| body: queryString.toString(), | ||
| } | ||
| ).catch(error => { | ||
| return { error } | ||
| }) | ||
| if (tokens.error) { | ||
| const error = createError({ | ||
| statusCode: 401, | ||
| message: `OIDC login failed: ${tokens.error?.data?.error_description || 'Unknown error'}`, | ||
| data: tokens | ||
| }) | ||
| if (!onError) throw error | ||
| return onError(event, error) | ||
| } | ||
|  | ||
| const tokenType = tokens.token_type | ||
| const accessToken = tokens.access_token | ||
| const userInfoUrl = config.userinfoUrl || '' | ||
|  | ||
| // Request userinfo. | ||
| const user: any = await ofetch(userInfoUrl, { | ||
| headers: { | ||
| Authorization: `${tokenType} ${accessToken}` | ||
| } | ||
| }) | ||
|  | ||
| return onSuccess(event, { | ||
| tokens, | ||
| user | ||
| }) | ||
| }) | ||
| } | 
  
    
      This file contains hidden or 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,27 @@ | ||
| import type { H3Error } from 'h3' | ||
|  | ||
| export type configValidationResult = { | ||
| valid: boolean, | ||
| error?: H3Error | ||
| } | ||
|  | ||
| export function validateConfig(config: any, requiredKeys: string[]): configValidationResult { | ||
| const missingKeys: string[] = [] | ||
| requiredKeys.forEach(key => { | ||
| if (!config[key]) { | ||
| missingKeys.push(key) | ||
| } | ||
| }) | ||
| if (missingKeys.length) { | ||
| const error = createError({ | ||
| statusCode: 500, | ||
| message: `Missing config keys: ${missingKeys.join(', ')}. Please pass the required parameters either as env variables or as part of the config parameter.` | ||
| }) | ||
|  | ||
| return { | ||
| valid: false, | ||
| error | ||
| } | ||
| } | ||
| return { valid: true } | ||
| } | 
  
    
      This file contains hidden or 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
    
  
  
    
              
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There is a remainder of a merge conflict here