Skip to content
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

Added support for PKCE extension for Authorization code grant. #1945

Merged
merged 3 commits into from
Sep 15, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ <h3 class="pt-0">Authorization
<label for="authServer" class="text-monospace form-label"
data-bind="text: $component.authorizationServer().displayName"></label>
</div>
<div class="col-6">
<div class="col-7">
<div class="form-group">
<select id="authServer" class="form-control"
data-bind="options: $component.authorizationServer().grantTypes, value: $component.selectedGrantType, optionsCaption: 'No auth'">
Expand All @@ -30,7 +30,7 @@ <h3 class="pt-0">Authorization
<div class="col-4">
<label for="username" class="text-monospace form-label">Username</label>
</div>
<div class="col-6">
<div class="col-7">
<div class="form-group">
<input type="text" id="username" class="form-control" data-bind="textInput: $component.username" />
</div>
Expand All @@ -40,7 +40,7 @@ <h3 class="pt-0">Authorization
<div class="col-4">
<label for="password" class="text-monospace form-label">Password</label>
</div>
<div class="col-6">
<div class="col-7">
<div class="form-group">
<input type="password" id="password" class="form-control" data-bind="textInput: $component.password" />
<span class="invalid-feedback" data-bind="text: $component.authorizationError"></span>
Expand All @@ -50,7 +50,7 @@ <h3 class="pt-0">Authorization
<div class="row flex flex-row">
<div class="col-4">
</div>
<div class="col-6">
<div class="col-7">
<div class="form-group">
<button class="button button-primary"
data-bind="click: $component.authenticateOAuthWithPassword">Authorize</button>
Expand All @@ -69,7 +69,7 @@ <h3 class="pt-0">Authorization
Subscription key
</label>
</div>
<div class="col-6">
<div class="col-7">
<div class="form-group">
<!-- ko if: $component.products() && $component.products().length > 0 -->
<select id="subscriptionKey" class="form-control" data-bind="value: $component.selectedSubscriptionKey">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ <h3>Host</h3>
Hostname
</label>
</div>
<div class="col-6">
<div class="col-7">
<div class="form-group">
<!-- ko if: $component.hostnameSelectionEnabled -->
<select id="hostname" class="form-control" data-bind="value: $component.selectedHostname">
Expand All @@ -72,7 +72,7 @@ <h3>Host</h3>
Wildcard segment
</label>
</div>
<div class="col-6">
<div class="col-7">
<div class="form-group">
<input id="wildcardSegment" type="text" autocomplete="off" class="form-control form-control-sm"
placeholder="name" spellcheck="false"
Expand Down Expand Up @@ -105,7 +105,7 @@ <h3>Parameters
<label class="text-monospace form-label" data-bind="text: parameter.name">
</label>
</div>
<div class="col-6">
<div class="col-7">
<div class="form-group">
<!-- ko if: parameter.options.length > 0 -->
<select class="form-control" aria-label="Parameter value"
Expand Down
6 changes: 6 additions & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,12 @@ export enum GrantTypes {
*/
authorizationCode = "authorization_code",

/**
* Proof Key for Code Exchange (abbreviated PKCE) is an extension to the authorization code
* flow to prevent CSRF and authorization code injection attacks.
*/
authorizationCodeWithPkce = "authorization_code (PKCE)",

/**
* The Client Credentials grant type is used by clients to obtain an access token outside of
* the context of a user.
Expand Down
26 changes: 26 additions & 0 deletions src/contracts/oauthTokenResponse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
export interface OAuthTokenResponse {
/**
* Access token.
*/
access_token: string;

/**
* Type of the access token, e.g. `Bearer`.
*/
token_type: string;

/**
* Expiration date and time, e.g. `1663205603`
*/
expires_on: string;

/**
* Base64-encoded ID token.
*/
id_token: string;

/**
* Refresh token.
*/
refresh_token: string;
}
3 changes: 3 additions & 0 deletions src/models/authorizationServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ export class AuthorizationServer {
case "authorizationCode":
convertedResult = "authorization_code";
break;
case "authorizationCodeWithPkce":
convertedResult = "authorization_code (PKCE)";
break;
case "implicit":
convertedResult = "implicit";
break;
Expand Down
3 changes: 2 additions & 1 deletion src/models/knownMimeTypes.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export enum KnownMimeTypes {
FormData = "multipart/form-data",
Json = "application/json",
Xml = "text/xml"
Xml = "text/xml",
UrlEncodedForm = "application/x-www-form-urlencoded"
}
96 changes: 95 additions & 1 deletion src/services/oauthService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { Utils } from "../utils";
import { GrantTypes } from "./../constants";
import { UnauthorizedError } from "./../errors/unauthorizedError";
import { BackendService } from "./backendService";
import { OAuthTokenResponse } from "../contracts/oauthTokenResponse";


export class OAuthService {
Expand All @@ -19,6 +20,25 @@ export class OAuthService {
private readonly logger: Logger
) { }

private async generateCodeChallenge(codeVerifier: string): Promise<string> {
const digest = await crypto.subtle.digest("SHA-256",
new TextEncoder().encode(codeVerifier));

return btoa(String.fromCharCode(...new Uint8Array(digest)))
.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_")
}

private generateRandomString(length: number): string {
let text = "";
const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

for (let i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}

return text;
}

public async getAuthServer(authorizationServerId: string, openidProviderId: string): Promise<AuthorizationServer> {
try {
if (authorizationServerId) {
Expand Down Expand Up @@ -58,6 +78,11 @@ export class OAuthService {
accessToken = await this.authenticateCode(backendUrl, authorizationServer);
break;

case GrantTypes.authorizationCodeWithPkce:
this.logger.trackEvent("TestConsoleOAuth", { grantType: GrantTypes.authorizationCodeWithPkce });
accessToken = await this.authenticateCodeWithPkce(backendUrl, authorizationServer);
break;

case GrantTypes.clientCredentials:
this.logger.trackEvent("TestConsoleOAuth", { grantType: GrantTypes.clientCredentials });
accessToken = await this.authenticateClientCredentials(backendUrl, authorizationServer, apiName);
Expand Down Expand Up @@ -149,8 +174,9 @@ export class OAuthService {
try {
window.open(oauthClient.code.getUri(), "_blank", "width=400,height=500");

const receiveMessage = async (event: MessageEvent) => {
const receiveMessage = async (event: MessageEvent): Promise<void> => {
if (!event.data["accessToken"]) {
alert("Unable to authenticate due to internal error.");
return;
}

Expand All @@ -167,6 +193,74 @@ export class OAuthService {
});
}

public async authenticateCodeWithPkce(backendUrl: string, authorizationServer: AuthorizationServer): Promise<string> {
const redirectUri = `${backendUrl}/signin-oauth/code-pkce/callback/${authorizationServer.name}`;
const codeVerifier = this.generateRandomString(64);
const challengeMethod = crypto.subtle ? "S256" : "plain"

const codeChallenge = challengeMethod === "S256"
? await this.generateCodeChallenge(codeVerifier)
: codeVerifier

sessionStorage.setItem("code_verifier", codeVerifier);

const args = new URLSearchParams({
response_type: "code",
client_id: authorizationServer.clientId,
code_challenge_method: challengeMethod,
code_challenge: codeChallenge,
redirect_uri: redirectUri,
scope: authorizationServer.scopes.join(" ")
});

return new Promise((resolve, reject) => {
try {
window.open(authorizationServer.authorizationEndpoint + "/?" + args, "_blank", "width=400,height=500");

const receiveMessage = async (event: MessageEvent): Promise<void> => {
const authorizationCode = event.data["code"];

if (!authorizationCode) {
alert("Unable to authenticate due to internal error.");
return;
}

const body = new URLSearchParams({
client_id: authorizationServer.clientId,
code_verifier: sessionStorage.getItem("code_verifier"),
grant_type: GrantTypes.authorizationCode,
redirect_uri: redirectUri,
code: authorizationCode
});

const response = await this.httpClient.send<OAuthTokenResponse>({
url: authorizationServer.tokenEndpoint,
method: HttpMethod.post,
headers: [{ name: KnownHttpHeaders.ContentType, value: KnownMimeTypes.UrlEncodedForm }],
body: body.toString()
});

if (response.statusCode === 400) {
const error = response.toText();
alert(error);
resolve(null);
}

const tokenResponse = response.toObject();
const accessToken = tokenResponse.access_token;
const accessTokenType = tokenResponse.token_type;

resolve(`${Utils.toTitleCase(accessTokenType)} ${accessToken}`);
};

window.addEventListener("message", receiveMessage, false);
}
catch (error) {
reject(error);
}
});
}

/**
* Acquires access token using "client credentials" grant flow.
* @param backendUrl {string} Portal backend URL.
Expand Down