-
Notifications
You must be signed in to change notification settings - Fork 126
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #885 from tirthct/ocm-4961
OCM-4961 | Feat | Add authentication using OAuth2 and PCKE
- Loading branch information
Showing
7 changed files
with
239 additions
and
39 deletions.
There are no files selected for viewing
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,122 @@ | ||
package authentication | ||
|
||
import ( | ||
"context" | ||
"crypto/tls" | ||
"fmt" | ||
"github.com/skratchdot/open-golang/open" | ||
"golang.org/x/oauth2" | ||
"io" | ||
"log" | ||
"net/http" | ||
"net/url" | ||
"sync" | ||
"time" | ||
) | ||
|
||
var ( | ||
conf *oauth2.Config | ||
ctx context.Context | ||
verifier string | ||
authToken string | ||
) | ||
|
||
const ( | ||
RedirectURL = "http://127.0.0.1" | ||
RedirectPort = "9998" | ||
DefaultAuthURL = "https://sso.redhat.com/auth/realms/redhat-external/protocol/openid-connect/auth" | ||
CallbackHandler = "/oauth/callback" | ||
) | ||
|
||
func callbackHandler(w http.ResponseWriter, r *http.Request) { | ||
queryParts, _ := url.ParseQuery(r.URL.RawQuery) | ||
|
||
// Use the authorization code that is pushed to the redirect URL | ||
code := queryParts["code"][0] | ||
|
||
// Exchange will do the handshake to retrieve the initial access token. | ||
tok, err := conf.Exchange(ctx, code, oauth2.VerifierOption(verifier)) | ||
if err != nil { | ||
log.Fatal(err) | ||
} | ||
|
||
// Get the access token and ask user to go back to CLI | ||
authToken = tok.AccessToken | ||
_, err = io.WriteString(w, "Login successful! Please close this window and return back to CLI") | ||
if err != nil { | ||
log.Fatal(err) | ||
} | ||
} | ||
|
||
func serve(wg *sync.WaitGroup) *http.Server { | ||
server := &http.Server{Addr: fmt.Sprintf(":%s", RedirectPort)} | ||
http.HandleFunc(CallbackHandler, callbackHandler) | ||
go func() { | ||
defer wg.Done() // let main know we are done cleaning up | ||
|
||
// always returns error. ErrServerClosed on graceful close | ||
if err := server.ListenAndServe(); err != http.ErrServerClosed { | ||
// unexpected error. port in use? | ||
log.Fatalf("ListenAndServe(): %v", err) | ||
} | ||
}() | ||
|
||
// returning reference so caller can call Shutdown() | ||
return server | ||
} | ||
|
||
func shutdown(server *http.Server) { | ||
if err := server.Shutdown(context.TODO()); err != nil { | ||
log.Fatalf("HTTP shutdown error: %v", err) | ||
} | ||
} | ||
|
||
func VerifyLogin(clientID string) (string, error) { | ||
authToken = "" | ||
ctx = context.Background() | ||
// Create config for OAuth2, redirect to localhost for callback verification and retrieving tokens | ||
conf = &oauth2.Config{ | ||
ClientID: clientID, | ||
ClientSecret: "", | ||
Scopes: []string{"openid"}, | ||
Endpoint: oauth2.Endpoint{ | ||
AuthURL: DefaultAuthURL, | ||
TokenURL: DefaultTokenURL, | ||
}, | ||
RedirectURL: fmt.Sprintf("%s:%s%s", RedirectURL, RedirectPort, CallbackHandler), | ||
} | ||
verifier = oauth2.GenerateVerifier() | ||
|
||
// add transport for self-signed certificate to context | ||
tr := &http.Transport{ | ||
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, | ||
} | ||
sslcli := &http.Client{Transport: tr} | ||
ctx = context.WithValue(ctx, oauth2.HTTPClient, sslcli) | ||
|
||
// Create URL with PKCE | ||
url := conf.AuthCodeURL("state", oauth2.AccessTypeOffline, oauth2.S256ChallengeOption(verifier)) | ||
|
||
httpServerExitDone := &sync.WaitGroup{} | ||
|
||
httpServerExitDone.Add(1) | ||
server := serve(httpServerExitDone) | ||
|
||
err := open.Run(url) | ||
if err != nil { | ||
return authToken, err | ||
} | ||
fiveMinTimer := time.Now().Local().Add(time.Minute * 5) | ||
|
||
// Wait for the user to finish auth process, and return back with authToken. Otherwise, return an error after 5 mins | ||
for { | ||
if authToken != "" { | ||
shutdown(server) | ||
return authToken, nil | ||
} | ||
if time.Now().After(fiveMinTimer) { | ||
shutdown(server) | ||
return authToken, fmt.Errorf("Time expired") | ||
} | ||
} | ||
} |
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 |
---|---|---|
@@ -0,0 +1,53 @@ | ||
// This example shows how to retrieve the collection of capabilities. | ||
|
||
package main | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"github.com/openshift-online/ocm-sdk-go/authentication" | ||
"os" | ||
|
||
sdk "github.com/openshift-online/ocm-sdk-go" | ||
"github.com/openshift-online/ocm-sdk-go/logging" | ||
) | ||
|
||
func main() { | ||
// Create a context: | ||
ctx := context.Background() | ||
|
||
// Create a logger that has the debug level enabled: | ||
logger, err := logging.NewGoLoggerBuilder(). | ||
Debug(true). | ||
Build() | ||
if err != nil { | ||
fmt.Fprintf(os.Stderr, "Can't build logger: %v\n", err) | ||
os.Exit(1) | ||
} | ||
|
||
// Create the connection, and remember to close it: | ||
token, err := authentication.VerifyLogin("ocm-cli") | ||
if err != nil { | ||
fmt.Fprintf(os.Stderr, "Can't get token: %v\n", err) | ||
os.Exit(1) | ||
} | ||
connection, err := sdk.NewConnectionBuilder(). | ||
Logger(logger). | ||
Tokens(token). | ||
BuildContext(ctx) | ||
if err != nil { | ||
fmt.Fprintf(os.Stderr, "Can't build connection: %v\n", err) | ||
os.Exit(1) | ||
} | ||
defer connection.Close() | ||
|
||
collection := connection.AccountsMgmt().V1().CurrentAccount() | ||
|
||
// Retrieve current account information | ||
_, err = collection.Get(). | ||
SendContext(ctx) | ||
if err != nil { | ||
fmt.Fprintf(os.Stderr, "Can't retrieve capabilities: %s\n", err) | ||
os.Exit(1) | ||
} | ||
} |
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
Oops, something went wrong.