From bd5df8e8a593a57250fea30a901026b187ff6100 Mon Sep 17 00:00:00 2001 From: Haisheng W - M Date: Wed, 17 Aug 2022 12:40:50 -0700 Subject: [PATCH] Adds Auth0 oauth2 plugin --- src/Yesod/Auth/OAuth2/Auth0.hs | 53 ++++++++++++++++++++++++++++++++++ yesod-auth-oauth2.cabal | 3 +- 2 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 src/Yesod/Auth/OAuth2/Auth0.hs diff --git a/src/Yesod/Auth/OAuth2/Auth0.hs b/src/Yesod/Auth/OAuth2/Auth0.hs new file mode 100644 index 0000000..dc6af7c --- /dev/null +++ b/src/Yesod/Auth/OAuth2/Auth0.hs @@ -0,0 +1,53 @@ +{-# LANGUAGE OverloadedStrings #-} +-- | +-- OAuth2 plugin for +-- +-- * Authenticates against specific auth0 tenant +-- * Uses Auth0 user id (a.k.a [sub](https://auth0.com/docs/api/authentication#get-user-info)) as credentials identifier +-- +module Yesod.Auth.OAuth2.Auth0 + (oauth2Auth0HostScopes + , defaultAuth0Scopes) where + +import Data.Aeson as Aeson +import qualified Data.Text as T +import Yesod.Auth.OAuth2.Prelude +import Prelude + +-- | https://auth0.com/docs/api/authentication#get-user-info +newtype User = User T.Text + +instance FromJSON User where + parseJSON = withObject "User" $ \o -> + User <$> o .: "sub" + +-- | https://auth0.com/docs/get-started/apis/scopes/openid-connect-scopes#standard-claims +defaultAuth0Scopes :: [Text] +defaultAuth0Scopes = ["openid"] + +pluginName :: Text +pluginName = "auth0" + +oauth2Auth0HostScopes :: YesodAuth m => URI -> [Text] -> Text -> Text -> AuthPlugin m +oauth2Auth0HostScopes host scopes clientId clientSecret = + authOAuth2 pluginName oauth2 $ \manager token -> do + (User uid, userResponse) <- + authGetProfile pluginName manager token (host `withPath` "/userinfo") + pure + Creds + { credsPlugin = pluginName, + credsIdent = uid, + credsExtra = setExtra token userResponse + } + where + oauth2 = + OAuth2 + { oauth2ClientId = clientId, + oauth2ClientSecret = Just clientSecret, + oauth2AuthorizeEndpoint = + host + `withPath` "/authorize" + `withQuery` [scopeParam " " scopes], + oauth2TokenEndpoint = host `withPath` "/oauth/token", + oauth2RedirectUri = Nothing + } diff --git a/yesod-auth-oauth2.cabal b/yesod-auth-oauth2.cabal index a508d4c..83e3a23 100644 --- a/yesod-auth-oauth2.cabal +++ b/yesod-auth-oauth2.cabal @@ -4,7 +4,7 @@ cabal-version: 1.12 -- -- see: https://github.com/sol/hpack -- --- hash: 233909874fdbdbd71fa70c49f5a4223b4150b85d9415dbbed7fde2fff9e5ebcf +-- hash: a1a4e1ae0e3bbc0c5aea847e950613465bc5361c9bd1a1beedb20d7259b0ad8f name: yesod-auth-oauth2 version: 0.7.0.1 @@ -39,6 +39,7 @@ library UnliftIO.Except URI.ByteString.Extension Yesod.Auth.OAuth2 + Yesod.Auth.OAuth2.Auth0 Yesod.Auth.OAuth2.AzureAD Yesod.Auth.OAuth2.BattleNet Yesod.Auth.OAuth2.Bitbucket