From ef44378336fd193c9880aadd466aded6501fa345 Mon Sep 17 00:00:00 2001 From: Chanaka Lakmal Date: Sat, 12 Dec 2020 09:29:20 +0530 Subject: [PATCH 1/9] Update module for swan lake design --- oauth2-ballerina/inbound_oauth2_provider.bal | 113 +++---- oauth2-ballerina/oauth2_errors.bal | 17 -- oauth2-ballerina/outbound_oauth2_provider.bal | 276 +++++++++--------- 3 files changed, 180 insertions(+), 226 deletions(-) diff --git a/oauth2-ballerina/inbound_oauth2_provider.bal b/oauth2-ballerina/inbound_oauth2_provider.bal index e86226a4..c85b6703 100644 --- a/oauth2-ballerina/inbound_oauth2_provider.bal +++ b/oauth2-ballerina/inbound_oauth2_provider.bal @@ -14,13 +14,54 @@ // specific language governing permissions and limitations // under the License. -import ballerina/auth; import ballerina/cache; import ballerina/log; import ballerina/stringutils; import ballerina/time; -type JsonMap map; +# Represents the introspection server configurations. +# +# + url - URL of the introspection server +# + tokenTypeHint - A hint about the type of the token submitted for introspection +# + oauth2Cache - Cache used to store the OAuth2 token and other related information +# + defaultTokenExpTimeInSeconds - Expiration time of the tokens if introspection response does not contain an `exp` field +# + clientConfig - HTTP client configurations which calls the introspection server +public type IntrospectionServerConfig record {| + string url; + string tokenTypeHint?; + cache:Cache oauth2Cache?; + int defaultTokenExpTimeInSeconds = 3600; + ClientConfiguration clientConfig = {}; +|}; + +# Represents the introspection server response. +# +# + active - Boolean indicator of whether or not the presented token is currently active +# + scopes - A JSON string containing a space-separated list of scopes associated with this token +# + clientId - Client identifier for the OAuth 2.0 client, which requested this token +# + username - Resource owner who authorized this token +# + tokenType - Type of the token +# + exp - Expiry time (seconds since the Epoch) +# + iat - Time when the token was issued originally (seconds since the Epoch) +# + nbf - Token is not to be used before this time (seconds since the Epoch) +# + sub - Subject of the token +# + aud - Intended audience of the token +# + iss - Issuer of the token +# + jti - String identifier for the token +public type IntrospectionResponse record {| + boolean active; + string scopes?; + string clientId?; + string username?; + string tokenType?; + int exp?; + int iat?; + int nbf?; + string sub?; + string aud?; + string iss?; + string jti?; +|}; # Represents the inbound OAuth2 provider, which calls the introspection server, validates the received credentials, # and performs authentication and authorization. The `oauth2:InboundOAuth2Provider` is an implementation of the @@ -33,14 +74,12 @@ type JsonMap map; # ``` public class InboundOAuth2Provider { - *auth:InboundAuthProvider; - IntrospectionServerConfig introspectionServerConfig; # Provides authentication based on the provided introspection configurations. # # + introspectionServerConfig - OAuth2 introspection server configurations - public function init(IntrospectionServerConfig introspectionServerConfig) { + public isolated function init(IntrospectionServerConfig introspectionServerConfig) { self.introspectionServerConfig = introspectionServerConfig; } @@ -51,24 +90,16 @@ public class InboundOAuth2Provider { # # + credential - OAuth2 token to be authenticated # + return - `true` if authentication is successful, `false` otherwise, or else an `auth:Error` if an error occurred - public function authenticate(string credential) returns boolean|auth:Error { + public isolated function authorize(string credential) returns IntrospectionResponse|Error { if (credential == "") { - return false; + return prepareError("Credential cannot be empty."); } IntrospectionResponse|Error validationResult = validateOAuth2Token(credential, self.introspectionServerConfig); if (validationResult is IntrospectionResponse) { - if (validationResult.active) { - auth:setInvocationContext("oauth2", credential, validationResult?.username, - getScopes(validationResult?.scopes)); - map|error introspectionResponseMap = validationResult.cloneWithType(JsonMap); - if (introspectionResponseMap is map) { - auth:setInvocationContext(claims = introspectionResponseMap); - } - } - return validationResult.active; + return validationResult; } else { - return prepareAuthError("OAuth2 validation failed.", validationResult); + return prepareError("OAuth2 validation failed.", validationResult); } } } @@ -200,10 +231,6 @@ isolated function validateFromCache(cache:Cache oauth2Cache, string token) retur } } -# Reads the scope(s) of the user with the given username. -# -# + scopes - Set of scopes seperated with a space -# + return - Array of groups for the user who is denoted by the username isolated function getScopes(string? scopes) returns string[] { if (scopes is ()) { return []; @@ -215,47 +242,3 @@ isolated function getScopes(string? scopes) returns string[] { return stringutils:split(scopeVal, " "); } } - -# Represents the introspection server configurations. -# -# + url - URL of the introspection server -# + tokenTypeHint - A hint about the type of the token submitted for introspection -# + oauth2Cache - Cache used to store the OAuth2 token and other related information -# + defaultTokenExpTimeInSeconds - Expiration time of the tokens if introspection response does not contain an `exp` field -# + clientConfig - HTTP client configurations which calls the introspection server -public type IntrospectionServerConfig record {| - string url; - string tokenTypeHint?; - cache:Cache oauth2Cache?; - int defaultTokenExpTimeInSeconds = 3600; - ClientConfiguration clientConfig = {}; -|}; - -# Represents the introspection server response. -# -# + active - Boolean indicator of whether or not the presented token is currently active -# + scopes - A JSON string containing a space-separated list of scopes associated with this token -# + clientId - Client identifier for the OAuth 2.0 client, which requested this token -# + username - Resource owner who authorized this token -# + tokenType - Type of the token -# + exp - Expiry time (seconds since the Epoch) -# + iat - Time when the token was issued originally (seconds since the Epoch) -# + nbf - Token is not to be used before this time (seconds since the Epoch) -# + sub - Subject of the token -# + aud - Intended audience of the token -# + iss - Issuer of the token -# + jti - String identifier for the token -public type IntrospectionResponse record {| - boolean active; - string scopes?; - string clientId?; - string username?; - string tokenType?; - int exp?; - int iat?; - int nbf?; - string sub?; - string aud?; - string iss?; - string jti?; -|}; diff --git a/oauth2-ballerina/oauth2_errors.bal b/oauth2-ballerina/oauth2_errors.bal index c9a2584b..b8a3c99f 100644 --- a/oauth2-ballerina/oauth2_errors.bal +++ b/oauth2-ballerina/oauth2_errors.bal @@ -14,7 +14,6 @@ // specific language governing permissions and limitations // under the License. -import ballerina/auth; import ballerina/log; # Represents the OAuth2 distinct error. @@ -38,19 +37,3 @@ isolated function prepareError(string message, error? err = ()) returns Error { } return oauth2Error; } - -# Log and prepare `error` as a `auth:Error`. -# -# + message - Error message -# + err - `error` instance -# + return - Prepared `auth:Error` instance -isolated function prepareAuthError(string message, error? err = ()) returns auth:Error { - log:printError(message, err = err); - auth:Error authError; - if (err is error) { - authError = auth:AuthError(message, err); - } else { - authError = auth:AuthError(message); - } - return authError; -} diff --git a/oauth2-ballerina/outbound_oauth2_provider.bal b/oauth2-ballerina/outbound_oauth2_provider.bal index bf8d98ab..4f6dd3a0 100644 --- a/oauth2-ballerina/outbound_oauth2_provider.bal +++ b/oauth2-ballerina/outbound_oauth2_provider.bal @@ -14,120 +14,8 @@ // specific language governing permissions and limitations // under the License. -import ballerina/auth; import ballerina/time; -# Represents the grant type configs supported for OAuth2. -type GrantTypeConfig ClientCredentialsGrantConfig|PasswordGrantConfig|DirectTokenConfig; - -# Represents the outbound OAuth2 provider, which generates OAtuh2 tokens. This supports the client credentials grant type, -# password grant type, and the direct token mode, which sends the access token directly. -# The `oauth2:OutboundOAuth2Provider` is an implementation of the `auth:OutboundAuthProvider` interface. -# -# 1. Client Credentials Grant Type -# ```ballerina -# oauth2:OutboundOAuth2Provider oauth2Provider1 = new({ -# tokenUrl: "https://localhost:9196/oauth2/token", -# clientId: "3MVG9YDQS5WtC11paU2WcQjBB3L", -# clientSecret: "9205371918321623741", -# scopes: ["token-scope1", "token-scope2"] -# }); -# ``` -# -# 2. Password Grant Type -# ```ballerina -# oauth2:OutboundOAuth2Provider oauth2Provider5 = new({ -# tokenUrl: "https://localhost:9196/oauth2/token/authorize/header", -# username: "johndoe", -# password: "A3ddj3w", -# clientId: "3MVG9YDQS5WtC11paU2WcQjBB3L", -# clientSecret: "9205371918321623741", -# scopes: ["token-scope1", "token-scope2"] -# }); -# ``` -# -# 3. Direct Token Mode -# ```ballerina -# oauth2:OutboundOAuth2Provider oauth2Provider13 = new({ -# accessToken: "2YotnFZFEjr1zCsicMWpAA", -# refreshConfig: { -# refreshUrl: "https://localhost:9196/oauth2/token/refresh", -# refreshToken: "XlfBs91yquexJqDaKEMzVg==", -# clientId: "3MVG9YDQS5WtC11paU2WcQjBB3L", -# clientSecret: "9205371918321623741", -# scopes: ["token-scope1", "token-scope2"] -# } -# }); -# ``` -public class OutboundOAuth2Provider { - - *auth:OutboundAuthProvider; - - GrantTypeConfig? oauth2ProviderConfig; - OutboundOAuth2CacheEntry oauth2CacheEntry; - - # Provides authentication based on the provided OAuth2 configuration. - # - # + oauth2ProviderConfig - Outbound OAuth2 provider configurations - public function init(GrantTypeConfig? oauth2ProviderConfig = ()) { - self.oauth2ProviderConfig = oauth2ProviderConfig; - self.oauth2CacheEntry = { - accessToken: "", - refreshToken: "", - expTime: 0 - }; - } - - # Generate a token for the OAuth2 authentication. - # ```ballerina - # string:auth:Error token = outboundOAuth2Provider.generateToken(); - # ``` - # - # + return - Generated `string` token or else an `auth:Error` if an error occurred - public function generateToken() returns string|auth:Error { - GrantTypeConfig? oauth2ProviderConfig = self.oauth2ProviderConfig; - if (oauth2ProviderConfig is ()) { - string? authToken = auth:getInvocationContext()?.token; - if (authToken is string) { - return authToken; - } - return prepareAuthError("Failed to generate OAuth2 token since OAuth2 provider config is not defined and OAuth2 token is not defined at auth:InvocationContext."); - } else { - string|Error authToken = generateOAuth2Token(oauth2ProviderConfig, self.oauth2CacheEntry); - if (authToken is string) { - return authToken; - } else { - return prepareAuthError("Failed to generate OAuth2 token.", authToken); - } - } - } - - # Inspects the incoming data and generates the token for the OAuth2 authentication. - # ```ballerina - # string:auth:Error? token = outboundOAuth2Provider.inspect(data); - # ``` - # - # + data - Map of data, which is extracted from the HTTP response - # + return - Generated `string` token, an `auth:Error` occurred while generating the token, or else - # `()` if nothing is to be returned - public function inspect(map data) returns string|auth:Error? { - GrantTypeConfig? oauth2ProviderConfig = self.oauth2ProviderConfig; - if (oauth2ProviderConfig is ()) { - return (); - } else { - if (data["STATUS_CODE"] == 401) { - string|Error authToken = inspectAuthTokenForOAuth2(oauth2ProviderConfig, self.oauth2CacheEntry); - if (authToken is string) { - return authToken; - } else { - return prepareAuthError("Failed to generate OAuth2 token at inspection.", authToken); - } - } - return (); - } - } -} - # The data structure, which is used to configure the OAuth2 client credentials grant type. # # + tokenUrl - Token URL for the authorization endpoint @@ -262,41 +150,141 @@ type RequestConfig record {| CredentialBearer credentialBearer; |}; +# Represents the grant type configs supported for OAuth2. +public type GrantConfig ClientCredentialsGrantConfig|PasswordGrantConfig|DirectTokenConfig; + +# Represents the outbound OAuth2 provider, which generates OAtuh2 tokens. This supports the client credentials grant type, +# password grant type, and the direct token mode, which sends the access token directly. +# The `oauth2:OutboundOAuth2Provider` is an implementation of the `auth:OutboundAuthProvider` interface. +# +# 1. Client Credentials Grant Type +# ```ballerina +# oauth2:OutboundOAuth2Provider oauth2Provider1 = new({ +# tokenUrl: "https://localhost:9196/oauth2/token", +# clientId: "3MVG9YDQS5WtC11paU2WcQjBB3L", +# clientSecret: "9205371918321623741", +# scopes: ["token-scope1", "token-scope2"] +# }); +# ``` +# +# 2. Password Grant Type +# ```ballerina +# oauth2:OutboundOAuth2Provider oauth2Provider5 = new({ +# tokenUrl: "https://localhost:9196/oauth2/token/authorize/header", +# username: "johndoe", +# password: "A3ddj3w", +# clientId: "3MVG9YDQS5WtC11paU2WcQjBB3L", +# clientSecret: "9205371918321623741", +# scopes: ["token-scope1", "token-scope2"] +# }); +# ``` +# +# 3. Direct Token Mode +# ```ballerina +# oauth2:OutboundOAuth2Provider oauth2Provider13 = new({ +# accessToken: "2YotnFZFEjr1zCsicMWpAA", +# refreshConfig: { +# refreshUrl: "https://localhost:9196/oauth2/token/refresh", +# refreshToken: "XlfBs91yquexJqDaKEMzVg==", +# clientId: "3MVG9YDQS5WtC11paU2WcQjBB3L", +# clientSecret: "9205371918321623741", +# scopes: ["token-scope1", "token-scope2"] +# } +# }); +# ``` +public class OutboundOAuth2Provider { + + GrantConfig grantConfig; + OutboundOAuth2CacheEntry oauth2CacheEntry; + + # Provides authentication based on the provided OAuth2 configuration. + # + # + oauth2ProviderConfig - Outbound OAuth2 provider configurations + public isolated function init(GrantConfig grantConfig) { + self.grantConfig = grantConfig; + self.oauth2CacheEntry = { + accessToken: "", + refreshToken: "", + expTime: 0 + }; + } + + # Generate a token for the OAuth2 authentication. + # ```ballerina + # string:auth:Error token = outboundOAuth2Provider.generateToken(); + # ``` + # + # + return - Generated `string` token or else an `auth:Error` if an error occurred + public isolated function generateToken() returns string|Error { + string|Error authToken = generateOAuth2Token(self.grantConfig, self.oauth2CacheEntry); + if (authToken is string) { + return authToken; + } else { + return prepareError("Failed to generate OAuth2 token.", authToken); + } + } + + //# Inspects the incoming data and generates the token for the OAuth2 authentication. + //# ```ballerina + //# string:auth:Error? token = outboundOAuth2Provider.inspect(data); + //# ``` + //# + //# + data - Map of data, which is extracted from the HTTP response + //# + return - Generated `string` token, an `auth:Error` occurred while generating the token, or else + //# `()` if nothing is to be returned + //public function inspect(map data) returns string|auth:Error? { + // GrantConfig? grantConfig = self.grantConfig; + // if (oauth2ProviderConfig is ()) { + // return (); + // } else { + // if (data["STATUS_CODE"] == 401) { + // string|Error authToken = inspectAuthTokenForOAuth2(oauth2ProviderConfig, self.oauth2CacheEntry); + // if (authToken is string) { + // return authToken; + // } else { + // return prepareAuthError("Failed to generate OAuth2 token at inspection.", authToken); + // } + // } + // return (); + // } + //} +} + # Generates the OAuth2 token. # -# + authConfig - OAuth2 configurations +# + grantConfig - OAuth2 configurations # + oauth2CacheEntry - OAuth2 cache entry # + return - OAuth2 token or else an `oauth2:Error` if the validation failed -isolated function generateOAuth2Token(GrantTypeConfig authConfig, OutboundOAuth2CacheEntry oauth2CacheEntry) +isolated function generateOAuth2Token(GrantConfig grantConfig, OutboundOAuth2CacheEntry oauth2CacheEntry) returns string|Error { - if (authConfig is PasswordGrantConfig) { - return getOAuth2TokenForPasswordGrant(authConfig, oauth2CacheEntry); - } else if (authConfig is ClientCredentialsGrantConfig) { - return getOAuth2TokenForClientCredentialsGrant(authConfig, oauth2CacheEntry); + if (grantConfig is PasswordGrantConfig) { + return getOAuth2TokenForPasswordGrant(grantConfig, oauth2CacheEntry); + } else if (grantConfig is ClientCredentialsGrantConfig) { + return getOAuth2TokenForClientCredentialsGrant(grantConfig, oauth2CacheEntry); } else { - return getOAuth2TokenForDirectTokenMode(authConfig, oauth2CacheEntry); + return getOAuth2TokenForDirectTokenMode(grantConfig, oauth2CacheEntry); } } # Processes the OAuth2 token at the inspection flow. # -# + authConfig - OAuth2 configurations +# + grantConfig - OAuth2 configurations # + oauth2CacheEntry - OAuth2 cache entry # + return - OAuth2 token or else an `oauth2:Error` if the validation failed -isolated function inspectAuthTokenForOAuth2(GrantTypeConfig authConfig, OutboundOAuth2CacheEntry oauth2CacheEntry) +isolated function inspectAuthTokenForOAuth2(GrantConfig grantConfig, OutboundOAuth2CacheEntry oauth2CacheEntry) returns string|Error { - if (authConfig is PasswordGrantConfig) { - if (authConfig.retryRequest) { - return getOAuth2TokenForPasswordGrant(authConfig, oauth2CacheEntry); + if (grantConfig is PasswordGrantConfig) { + if (grantConfig.retryRequest) { + return getOAuth2TokenForPasswordGrant(grantConfig, oauth2CacheEntry); } - } else if (authConfig is ClientCredentialsGrantConfig) { - if (authConfig.retryRequest) { - return getOAuth2TokenForClientCredentialsGrant(authConfig, oauth2CacheEntry); + } else if (grantConfig is ClientCredentialsGrantConfig) { + if (grantConfig.retryRequest) { + return getOAuth2TokenForClientCredentialsGrant(grantConfig, oauth2CacheEntry); } } else { - if (authConfig.retryRequest) { - authConfig.accessToken = ""; - return getOAuth2TokenForDirectTokenMode(authConfig, oauth2CacheEntry); + if (grantConfig.retryRequest) { + grantConfig.accessToken = ""; + return getOAuth2TokenForDirectTokenMode(grantConfig, oauth2CacheEntry); } } return prepareError("Failed to get the access token since retry request is set as false."); @@ -304,14 +292,14 @@ isolated function inspectAuthTokenForOAuth2(GrantTypeConfig authConfig, Outbound # Processes the OAuth2 token for the password grant type. # -# + grantTypeConfig - Password grant type configurations +# + grantConfig - Password grant type configurations # + oauth2CacheEntry - OAuth2 cache entry # + return - OAuth2 token or else an `oauth2:Error` occurred during the HTTP client invocation or validation -isolated function getOAuth2TokenForPasswordGrant(PasswordGrantConfig grantTypeConfig, +isolated function getOAuth2TokenForPasswordGrant(PasswordGrantConfig grantConfig, OutboundOAuth2CacheEntry oauth2CacheEntry) returns string|Error { string cachedAccessToken = oauth2CacheEntry.accessToken; if (cachedAccessToken == "") { - return getAccessTokenFromAuthorizationRequest(grantTypeConfig, oauth2CacheEntry); + return getAccessTokenFromAuthorizationRequest(grantConfig, oauth2CacheEntry); } else { if (isOAuth2CacheEntryValid(oauth2CacheEntry)) { return cachedAccessToken; @@ -320,7 +308,7 @@ isolated function getOAuth2TokenForPasswordGrant(PasswordGrantConfig grantTypeCo if (isOAuth2CacheEntryValid(oauth2CacheEntry)) { return oauth2CacheEntry.accessToken; } else { - return getAccessTokenFromRefreshRequest(grantTypeConfig, oauth2CacheEntry); + return getAccessTokenFromRefreshRequest(grantConfig, oauth2CacheEntry); } } } @@ -329,15 +317,15 @@ isolated function getOAuth2TokenForPasswordGrant(PasswordGrantConfig grantTypeCo # Processes the OAuth2 token for the client credentials grant type. # -# + grantTypeConfig - Client credentials grant type configurations +# + grantConfig - Client credentials grant type configurations # + oauth2CacheEntry - OAuth2 cache entry # + return - OAuth2 token or else an `oauth2:Error` occurred during the HTTP client invocation or validation -isolated function getOAuth2TokenForClientCredentialsGrant(ClientCredentialsGrantConfig grantTypeConfig, +isolated function getOAuth2TokenForClientCredentialsGrant(ClientCredentialsGrantConfig grantConfig, OutboundOAuth2CacheEntry oauth2CacheEntry) returns string|Error { string cachedAccessToken = oauth2CacheEntry.accessToken; if (cachedAccessToken == "") { - return getAccessTokenFromAuthorizationRequest(grantTypeConfig, oauth2CacheEntry); + return getAccessTokenFromAuthorizationRequest(grantConfig, oauth2CacheEntry); } else { if (isOAuth2CacheEntryValid(oauth2CacheEntry)) { return cachedAccessToken; @@ -347,7 +335,7 @@ isolated function getOAuth2TokenForClientCredentialsGrant(ClientCredentialsGrant cachedAccessToken = oauth2CacheEntry.accessToken; return cachedAccessToken; } else { - return getAccessTokenFromAuthorizationRequest(grantTypeConfig, oauth2CacheEntry); + return getAccessTokenFromAuthorizationRequest(grantConfig, oauth2CacheEntry); } } } @@ -356,18 +344,18 @@ isolated function getOAuth2TokenForClientCredentialsGrant(ClientCredentialsGrant # Processes the OAuth2 token for the direct token mode. # -# + grantTypeConfig - Direct token mode configurations +# + grantConfig - Direct token mode configurations # + oauth2CacheEntry - OAuth2 cache entry # + return -OAuth2 token or else an `oauth2:Error` occurred during the HTTP client invocation or validation -isolated function getOAuth2TokenForDirectTokenMode(DirectTokenConfig grantTypeConfig, +isolated function getOAuth2TokenForDirectTokenMode(DirectTokenConfig grantConfig, OutboundOAuth2CacheEntry oauth2CacheEntry) returns string|Error { string cachedAccessToken = oauth2CacheEntry.accessToken; if (cachedAccessToken == "") { - string? directAccessToken = grantTypeConfig?.accessToken; + string? directAccessToken = grantConfig?.accessToken; if (directAccessToken is string && directAccessToken != "") { return directAccessToken; } else { - return getAccessTokenFromRefreshRequest(grantTypeConfig, oauth2CacheEntry); + return getAccessTokenFromRefreshRequest(grantConfig, oauth2CacheEntry); } } else { if (isOAuth2CacheEntryValid(oauth2CacheEntry)) { @@ -378,7 +366,7 @@ isolated function getOAuth2TokenForDirectTokenMode(DirectTokenConfig grantTypeCo cachedAccessToken = oauth2CacheEntry.accessToken; return cachedAccessToken; } else { - return getAccessTokenFromRefreshRequest(grantTypeConfig, oauth2CacheEntry); + return getAccessTokenFromRefreshRequest(grantConfig, oauth2CacheEntry); } } } @@ -539,7 +527,7 @@ isolated function prepareHeaders(RequestConfig config) returns map|Error string? clientSecret = config?.clientSecret; if (clientId is string && clientSecret is string) { string clientIdSecret = clientId + ":" + clientSecret; - headers["Authorization"] = auth:AUTH_SCHEME_BASIC + clientIdSecret.toBytes().toBase64(); + headers["Authorization"] = "Basic " + clientIdSecret.toBytes().toBase64(); } else { return prepareError("Client ID or client secret is not provided for client authentication."); } From ab44ec0272ac127552e7c3d35b18c430562edf2b Mon Sep 17 00:00:00 2001 From: Chanaka Lakmal Date: Tue, 15 Dec 2020 15:07:40 +0530 Subject: [PATCH 2/9] Update provider APIs --- ...{outbound_oauth2_provider.bal => client_oauth2_provider.bal} | 2 +- ...inbound_oauth2_provider.bal => listener_oauth2_provider.bal} | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename oauth2-ballerina/{outbound_oauth2_provider.bal => client_oauth2_provider.bal} (99%) rename oauth2-ballerina/{inbound_oauth2_provider.bal => listener_oauth2_provider.bal} (99%) diff --git a/oauth2-ballerina/outbound_oauth2_provider.bal b/oauth2-ballerina/client_oauth2_provider.bal similarity index 99% rename from oauth2-ballerina/outbound_oauth2_provider.bal rename to oauth2-ballerina/client_oauth2_provider.bal index 4f6dd3a0..6fa09673 100644 --- a/oauth2-ballerina/outbound_oauth2_provider.bal +++ b/oauth2-ballerina/client_oauth2_provider.bal @@ -192,7 +192,7 @@ public type GrantConfig ClientCredentialsGrantConfig|PasswordGrantConfig|DirectT # } # }); # ``` -public class OutboundOAuth2Provider { +public class ClientOAuth2Provider { GrantConfig grantConfig; OutboundOAuth2CacheEntry oauth2CacheEntry; diff --git a/oauth2-ballerina/inbound_oauth2_provider.bal b/oauth2-ballerina/listener_oauth2_provider.bal similarity index 99% rename from oauth2-ballerina/inbound_oauth2_provider.bal rename to oauth2-ballerina/listener_oauth2_provider.bal index c85b6703..d91c9b7a 100644 --- a/oauth2-ballerina/inbound_oauth2_provider.bal +++ b/oauth2-ballerina/listener_oauth2_provider.bal @@ -72,7 +72,7 @@ public type IntrospectionResponse record {| # }; # oauth2:InboundOAuth2Provider inboundOAuth2Provider = new(introspectionServerConfig); # ``` -public class InboundOAuth2Provider { +public class ListenerOAuth2Provider { IntrospectionServerConfig introspectionServerConfig; From 3f7b9553d56eb0ab05b789cdbb53fe6b24813c64 Mon Sep 17 00:00:00 2001 From: Chanaka Lakmal Date: Tue, 15 Dec 2020 16:29:01 +0530 Subject: [PATCH 3/9] Remove unused codes --- oauth2-ballerina/client_oauth2_provider.bal | 49 --------------------- 1 file changed, 49 deletions(-) diff --git a/oauth2-ballerina/client_oauth2_provider.bal b/oauth2-ballerina/client_oauth2_provider.bal index 6fa09673..fb689c56 100644 --- a/oauth2-ballerina/client_oauth2_provider.bal +++ b/oauth2-ballerina/client_oauth2_provider.bal @@ -223,31 +223,6 @@ public class ClientOAuth2Provider { return prepareError("Failed to generate OAuth2 token.", authToken); } } - - //# Inspects the incoming data and generates the token for the OAuth2 authentication. - //# ```ballerina - //# string:auth:Error? token = outboundOAuth2Provider.inspect(data); - //# ``` - //# - //# + data - Map of data, which is extracted from the HTTP response - //# + return - Generated `string` token, an `auth:Error` occurred while generating the token, or else - //# `()` if nothing is to be returned - //public function inspect(map data) returns string|auth:Error? { - // GrantConfig? grantConfig = self.grantConfig; - // if (oauth2ProviderConfig is ()) { - // return (); - // } else { - // if (data["STATUS_CODE"] == 401) { - // string|Error authToken = inspectAuthTokenForOAuth2(oauth2ProviderConfig, self.oauth2CacheEntry); - // if (authToken is string) { - // return authToken; - // } else { - // return prepareAuthError("Failed to generate OAuth2 token at inspection.", authToken); - // } - // } - // return (); - // } - //} } # Generates the OAuth2 token. @@ -266,30 +241,6 @@ isolated function generateOAuth2Token(GrantConfig grantConfig, OutboundOAuth2Cac } } -# Processes the OAuth2 token at the inspection flow. -# -# + grantConfig - OAuth2 configurations -# + oauth2CacheEntry - OAuth2 cache entry -# + return - OAuth2 token or else an `oauth2:Error` if the validation failed -isolated function inspectAuthTokenForOAuth2(GrantConfig grantConfig, OutboundOAuth2CacheEntry oauth2CacheEntry) - returns string|Error { - if (grantConfig is PasswordGrantConfig) { - if (grantConfig.retryRequest) { - return getOAuth2TokenForPasswordGrant(grantConfig, oauth2CacheEntry); - } - } else if (grantConfig is ClientCredentialsGrantConfig) { - if (grantConfig.retryRequest) { - return getOAuth2TokenForClientCredentialsGrant(grantConfig, oauth2CacheEntry); - } - } else { - if (grantConfig.retryRequest) { - grantConfig.accessToken = ""; - return getOAuth2TokenForDirectTokenMode(grantConfig, oauth2CacheEntry); - } - } - return prepareError("Failed to get the access token since retry request is set as false."); -} - # Processes the OAuth2 token for the password grant type. # # + grantConfig - Password grant type configurations From ff892da112ee66112c2d1a26365370662980344d Mon Sep 17 00:00:00 2001 From: Chanaka Lakmal Date: Tue, 15 Dec 2020 16:56:19 +0530 Subject: [PATCH 4/9] Update ballerina documentation --- oauth2-ballerina/client_oauth2_provider.bal | 77 +++++-------------- oauth2-ballerina/listener_oauth2_provider.bal | 20 +++-- oauth2-ballerina/oauth2_errors.bal | 2 +- 3 files changed, 29 insertions(+), 70 deletions(-) diff --git a/oauth2-ballerina/client_oauth2_provider.bal b/oauth2-ballerina/client_oauth2_provider.bal index fb689c56..b013d5c8 100644 --- a/oauth2-ballerina/client_oauth2_provider.bal +++ b/oauth2-ballerina/client_oauth2_provider.bal @@ -132,15 +132,8 @@ public type OutboundOAuth2CacheEntry record { int expTime; }; -# The data structure, which stores the values needed to prepare the HTTP request, which are to be sent to the -# authorization endpoint. -# -# + payload - Payload of the request -# + clientId - Client ID for the client credentials grant authentication -# + clientSecret - Client secret for the client credentials grant authentication -# + scopes - Scope(s) of the access request -# + parameters - Map of endpoint parameters use with the authorization endpoint -# + credentialBearer - Bearer of the authentication credentials, which is sent to the authorization endpoint +// The data structure, which stores the values needed to prepare the HTTP request, which are to be sent to the +// authorization endpoint. type RequestConfig record {| string payload; string clientId?; @@ -153,13 +146,12 @@ type RequestConfig record {| # Represents the grant type configs supported for OAuth2. public type GrantConfig ClientCredentialsGrantConfig|PasswordGrantConfig|DirectTokenConfig; -# Represents the outbound OAuth2 provider, which generates OAtuh2 tokens. This supports the client credentials grant type, +# Represents the client OAuth2 provider, which generates OAtuh2 tokens. This supports the client credentials grant type, # password grant type, and the direct token mode, which sends the access token directly. -# The `oauth2:OutboundOAuth2Provider` is an implementation of the `auth:OutboundAuthProvider` interface. # # 1. Client Credentials Grant Type # ```ballerina -# oauth2:OutboundOAuth2Provider oauth2Provider1 = new({ +# oauth2:ClientOAuth2Provider provider = new({ # tokenUrl: "https://localhost:9196/oauth2/token", # clientId: "3MVG9YDQS5WtC11paU2WcQjBB3L", # clientSecret: "9205371918321623741", @@ -169,7 +161,7 @@ public type GrantConfig ClientCredentialsGrantConfig|PasswordGrantConfig|DirectT # # 2. Password Grant Type # ```ballerina -# oauth2:OutboundOAuth2Provider oauth2Provider5 = new({ +# oauth2:ClientOAuth2Provider provider = new({ # tokenUrl: "https://localhost:9196/oauth2/token/authorize/header", # username: "johndoe", # password: "A3ddj3w", @@ -181,7 +173,7 @@ public type GrantConfig ClientCredentialsGrantConfig|PasswordGrantConfig|DirectT # # 3. Direct Token Mode # ```ballerina -# oauth2:OutboundOAuth2Provider oauth2Provider13 = new({ +# oauth2:ClientOAuth2Provider provider = new({ # accessToken: "2YotnFZFEjr1zCsicMWpAA", # refreshConfig: { # refreshUrl: "https://localhost:9196/oauth2/token/refresh", @@ -197,9 +189,9 @@ public class ClientOAuth2Provider { GrantConfig grantConfig; OutboundOAuth2CacheEntry oauth2CacheEntry; - # Provides authentication based on the provided OAuth2 configuration. + # Provides authentication based on the provided OAuth2 configurations. # - # + oauth2ProviderConfig - Outbound OAuth2 provider configurations + # + grantConfig - OAuth2 grant type configurations public isolated function init(GrantConfig grantConfig) { self.grantConfig = grantConfig; self.oauth2CacheEntry = { @@ -211,10 +203,10 @@ public class ClientOAuth2Provider { # Generate a token for the OAuth2 authentication. # ```ballerina - # string:auth:Error token = outboundOAuth2Provider.generateToken(); + # string:oauth2:Error token = provider.generateToken(); # ``` # - # + return - Generated `string` token or else an `auth:Error` if an error occurred + # + return - Generated `string` token or else an `oauth2:Error` if an error occurred public isolated function generateToken() returns string|Error { string|Error authToken = generateOAuth2Token(self.grantConfig, self.oauth2CacheEntry); if (authToken is string) { @@ -225,11 +217,7 @@ public class ClientOAuth2Provider { } } -# Generates the OAuth2 token. -# -# + grantConfig - OAuth2 configurations -# + oauth2CacheEntry - OAuth2 cache entry -# + return - OAuth2 token or else an `oauth2:Error` if the validation failed +// Generates the OAuth2 token. isolated function generateOAuth2Token(GrantConfig grantConfig, OutboundOAuth2CacheEntry oauth2CacheEntry) returns string|Error { if (grantConfig is PasswordGrantConfig) { @@ -241,11 +229,7 @@ isolated function generateOAuth2Token(GrantConfig grantConfig, OutboundOAuth2Cac } } -# Processes the OAuth2 token for the password grant type. -# -# + grantConfig - Password grant type configurations -# + oauth2CacheEntry - OAuth2 cache entry -# + return - OAuth2 token or else an `oauth2:Error` occurred during the HTTP client invocation or validation +// Processes the OAuth2 token for the password grant type. isolated function getOAuth2TokenForPasswordGrant(PasswordGrantConfig grantConfig, OutboundOAuth2CacheEntry oauth2CacheEntry) returns string|Error { string cachedAccessToken = oauth2CacheEntry.accessToken; @@ -266,11 +250,7 @@ isolated function getOAuth2TokenForPasswordGrant(PasswordGrantConfig grantConfig } } -# Processes the OAuth2 token for the client credentials grant type. -# -# + grantConfig - Client credentials grant type configurations -# + oauth2CacheEntry - OAuth2 cache entry -# + return - OAuth2 token or else an `oauth2:Error` occurred during the HTTP client invocation or validation +// Processes the OAuth2 token for the client credentials grant type. isolated function getOAuth2TokenForClientCredentialsGrant(ClientCredentialsGrantConfig grantConfig, OutboundOAuth2CacheEntry oauth2CacheEntry) returns string|Error { @@ -293,11 +273,7 @@ isolated function getOAuth2TokenForClientCredentialsGrant(ClientCredentialsGrant } } -# Processes the OAuth2 token for the direct token mode. -# -# + grantConfig - Direct token mode configurations -# + oauth2CacheEntry - OAuth2 cache entry -# + return -OAuth2 token or else an `oauth2:Error` occurred during the HTTP client invocation or validation +// Processes the OAuth2 token for the direct token mode. isolated function getOAuth2TokenForDirectTokenMode(DirectTokenConfig grantConfig, OutboundOAuth2CacheEntry oauth2CacheEntry) returns string|Error { string cachedAccessToken = oauth2CacheEntry.accessToken; @@ -324,11 +300,8 @@ isolated function getOAuth2TokenForDirectTokenMode(DirectTokenConfig grantConfig } } -# Checks the validity of the access token, which is in the cache. If the expiry time is 0, that means no expiry time is -# returned with the authorization request. This implies that the token is valid forever. -# -# + oauth2CacheEntry - OAuth2 cache entry -# + return - `true` if the access token is valid or else `false` +// Checks the validity of the access token, which is in the cache. If the expiry time is 0, that means no expiry time is +// returned with the authorization request. This implies that the token is valid forever. isolated function isOAuth2CacheEntryValid(OutboundOAuth2CacheEntry oauth2CacheEntry) returns boolean { int expTime = oauth2CacheEntry.expTime; if (expTime == 0) { @@ -341,11 +314,7 @@ isolated function isOAuth2CacheEntryValid(OutboundOAuth2CacheEntry oauth2CacheEn return false; } -# Requests an access token from the authorization endpoint using the provided configurations. -# -# + config - OAuth2 grant type configurations -# + oauth2CacheEntry - OAuth2 cache entry -# + return - Received OAuth2 access token or else an `oauth2:Error` occurred during the HTTP client invocation +// Requests an access token from the authorization endpoint using the provided configurations. isolated function getAccessTokenFromAuthorizationRequest(ClientCredentialsGrantConfig|PasswordGrantConfig config, OutboundOAuth2CacheEntry oauth2CacheEntry) returns string|Error { RequestConfig requestConfig; @@ -398,11 +367,7 @@ isolated function getAccessTokenFromAuthorizationRequest(ClientCredentialsGrantC return sendRequest(requestConfig, tokenUrl, clientConfig, oauth2CacheEntry, clockSkewInSeconds); } -# Requests an access token from the authorization endpoint using the provided refresh configurations. -# -# + config - Password grant type configuration or direct token configuration -# + oauth2CacheEntry - OAuth2 cache entry -# + return - Received access token or else an `oauth2:Error` occurred during the HTTP client invocation +// Requests an access token from the authorization endpoint using the provided refresh configurations. isolated function getAccessTokenFromRefreshRequest(PasswordGrantConfig|DirectTokenConfig config, OutboundOAuth2CacheEntry oauth2CacheEntry) returns string|Error { RequestConfig requestConfig; @@ -532,11 +497,7 @@ isolated function extractAccessToken(string response, OutboundOAuth2CacheEntry o } } -# Updates the OAuth2 token entry with the received JSON payload of the response. -# -# + responsePayload - Payload of the response -# + oauth2CacheEntry - OAuth2 cache entry -# + clockSkewInSeconds - Clock skew in seconds +// Updates the OAuth2 token entry with the received JSON payload of the response. isolated function updateOAuth2CacheEntry(json responsePayload, OutboundOAuth2CacheEntry oauth2CacheEntry, int clockSkewInSeconds) { int issueTime = time:currentTime().time; diff --git a/oauth2-ballerina/listener_oauth2_provider.bal b/oauth2-ballerina/listener_oauth2_provider.bal index d91c9b7a..3120d5c6 100644 --- a/oauth2-ballerina/listener_oauth2_provider.bal +++ b/oauth2-ballerina/listener_oauth2_provider.bal @@ -64,13 +64,12 @@ public type IntrospectionResponse record {| |}; # Represents the inbound OAuth2 provider, which calls the introspection server, validates the received credentials, -# and performs authentication and authorization. The `oauth2:InboundOAuth2Provider` is an implementation of the -# `auth:InboundAuthProvider` interface. +# and performs authentication and authorization. # ```ballerina -# oauth2:IntrospectionServerConfig introspectionServerConfig = { +# oauth2:IntrospectionServerConfig config = { # url: "https://localhost:9196/oauth2/token/introspect" # }; -# oauth2:InboundOAuth2Provider inboundOAuth2Provider = new(introspectionServerConfig); +# oauth2:ListenerOAuth2Provider provider = new(config); # ``` public class ListenerOAuth2Provider { @@ -85,11 +84,11 @@ public class ListenerOAuth2Provider { # Authenticates the provider OAuth2 tokens with an introspection endpoint. # ```ballerina - # boolean|auth:Error result = inboundOAuth2Provider.authenticate(""); + # boolean|oauth2:Error result = provider.authenticate(""); # ``` # # + credential - OAuth2 token to be authenticated - # + return - `true` if authentication is successful, `false` otherwise, or else an `auth:Error` if an error occurred + # + return - `oauth2:IntrospectionResponse` if authentication is successful, or else an `oauth2:Error` if an error occurred public isolated function authorize(string credential) returns IntrospectionResponse|Error { if (credential == "") { return prepareError("Credential cannot be empty."); @@ -104,16 +103,15 @@ public class ListenerOAuth2Provider { } } -# Validates the given OAuth2 token by calling the OAuth2 introspection endpoint. +# Validates the provided OAuth2 token by calling the OAuth2 introspection endpoint. # ```ballerina -# oauth2:IntrospectionResponse|oauth2:Error result = oauth2:validateOAuth2Token(token, introspectionServerConfig); +# oauth2:IntrospectionResponse|oauth2:Error result = oauth2:validate(token, introspectionServerConfig); # ``` # # + token - OAuth2 token, which needs to be validated # + config - OAuth2 introspection server configurations # + return - OAuth2 introspection server response or else an `oauth2:Error` if token validation fails -public isolated function validateOAuth2Token(string token, IntrospectionServerConfig config) - returns IntrospectionResponse|Error { +public isolated function validate(string token, IntrospectionServerConfig config) returns IntrospectionResponse|Error { cache:Cache? oauth2Cache = config?.oauth2Cache; if (oauth2Cache is cache:Cache && oauth2Cache.hasKey(token)) { IntrospectionResponse? response = validateFromCache(oauth2Cache, token); @@ -219,7 +217,7 @@ isolated function validateFromCache(cache:Cache oauth2Cache, string token) retur IntrospectionResponse response = cachedEntry; int? expTime = response?.exp; // The `expTime` can be `()`. This means that the `defaultTokenExpTimeInSeconds` is not exceeded yet. - // Hence, the token is still valid. If the `expTime` is given in int, convert this to the current time and + // Hence, the token is still valid. If the `expTime` is provided in int, convert this to the current time and // check if the expiry time is exceeded. if (expTime is () || expTime > (time:currentTime().time / 1000)) { return response; diff --git a/oauth2-ballerina/oauth2_errors.bal b/oauth2-ballerina/oauth2_errors.bal index b8a3c99f..2ce762d6 100644 --- a/oauth2-ballerina/oauth2_errors.bal +++ b/oauth2-ballerina/oauth2_errors.bal @@ -26,7 +26,7 @@ public type Error OAuth2Error; # # + message - Error message # + err - `error` instance -# + return - Prepared `Error` instance +# + return - Prepared `oauth2:Error` instance isolated function prepareError(string message, error? err = ()) returns Error { log:printError(message, err = err); Error oauth2Error; From 91248831f32936c24557a90123c6687ecbc4c642 Mon Sep 17 00:00:00 2001 From: Chanaka Lakmal Date: Tue, 15 Dec 2020 17:28:06 +0530 Subject: [PATCH 5/9] Refactor code --- oauth2-ballerina/client_oauth2_provider.bal | 5 ++--- oauth2-ballerina/listener_oauth2_provider.bal | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/oauth2-ballerina/client_oauth2_provider.bal b/oauth2-ballerina/client_oauth2_provider.bal index b013d5c8..b6a2951b 100644 --- a/oauth2-ballerina/client_oauth2_provider.bal +++ b/oauth2-ballerina/client_oauth2_provider.bal @@ -209,11 +209,10 @@ public class ClientOAuth2Provider { # + return - Generated `string` token or else an `oauth2:Error` if an error occurred public isolated function generateToken() returns string|Error { string|Error authToken = generateOAuth2Token(self.grantConfig, self.oauth2CacheEntry); - if (authToken is string) { - return authToken; - } else { + if (authToken is Error) { return prepareError("Failed to generate OAuth2 token.", authToken); } + return authToken; } } diff --git a/oauth2-ballerina/listener_oauth2_provider.bal b/oauth2-ballerina/listener_oauth2_provider.bal index 3120d5c6..b1c5d5af 100644 --- a/oauth2-ballerina/listener_oauth2_provider.bal +++ b/oauth2-ballerina/listener_oauth2_provider.bal @@ -94,7 +94,7 @@ public class ListenerOAuth2Provider { return prepareError("Credential cannot be empty."); } - IntrospectionResponse|Error validationResult = validateOAuth2Token(credential, self.introspectionServerConfig); + IntrospectionResponse|Error validationResult = validate(credential, self.introspectionServerConfig); if (validationResult is IntrospectionResponse) { return validationResult; } else { From 3b295c806e25d5fa5ae6aadb21dfbbef7b08df31 Mon Sep 17 00:00:00 2001 From: Chanaka Lakmal Date: Wed, 16 Dec 2020 20:24:20 +0530 Subject: [PATCH 6/9] Remove unused dependencies --- build.gradle | 36 --------------------------------- gradle.properties | 4 ---- oauth2-ballerina/Ballerina.toml | 5 ----- oauth2-ballerina/build.gradle | 2 -- 4 files changed, 47 deletions(-) diff --git a/build.gradle b/build.gradle index b571fe96..e534fc3e 100644 --- a/build.gradle +++ b/build.gradle @@ -24,17 +24,13 @@ plugins { } ext.ballerinaLangVersion = project.ballerinaLangVersion -ext.stdlibAuthVersion = project.stdlibAuthVersion ext.stdlibCacheVersion = project.stdlibCacheVersion ext.stdlibCryptoVersion = project.stdlibCryptoVersion ext.stdlibLogVersion = project.stdlibLogVersion ext.stdlibStringUtilsVersion = project.stdlibStringUtilsVersion ext.stdlibTimeVersion = project.stdlibTimeVersion // Transitive dependencies -ext.stdlibConfigVersion = project.stdlibConfigVersion -ext.stdlibIoVersion = project.stdlibIoVersion ext.stdlibRuntimeVersion = project.stdlibRuntimeVersion -ext.stdlibSystemVersion = project.stdlibSystemVersion ext.stdlibTaskVersion = project.stdlibTaskVersion allprojects { @@ -62,13 +58,6 @@ allprojects { password System.getenv("packagePAT") } } - maven { - url = 'https://maven.pkg.github.com/ballerina-platform/module-ballerina-auth' - credentials { - username System.getenv("packageUser") - password System.getenv("packagePAT") - } - } maven { url = 'https://maven.pkg.github.com/ballerina-platform/module-ballerina-cache' credentials { @@ -105,20 +94,6 @@ allprojects { } } // Transitive dependencies - maven { - url = 'https://maven.pkg.github.com/ballerina-platform/module-ballerina-config' - credentials { - username System.getenv("packageUser") - password System.getenv("packagePAT") - } - } - maven { - url = 'https://maven.pkg.github.com/ballerina-platform/module-ballerina-io' - credentials { - username System.getenv("packageUser") - password System.getenv("packagePAT") - } - } maven { url = 'https://maven.pkg.github.com/ballerina-platform/module-ballerina-runtime' credentials { @@ -126,13 +101,6 @@ allprojects { password System.getenv("packagePAT") } } - maven { - url = 'https://maven.pkg.github.com/ballerina-platform/module-ballerina-system' - credentials { - username System.getenv("packageUser") - password System.getenv("packagePAT") - } - } maven { url = 'https://maven.pkg.github.com/ballerina-platform/module-ballerina-task' credentials { @@ -151,17 +119,13 @@ subprojects { } dependencies { /* Standard libraries */ - ballerinaStdLibs "org.ballerinalang:auth-ballerina:${stdlibAuthVersion}" ballerinaStdLibs "org.ballerinalang:cache-ballerina:${stdlibCacheVersion}" ballerinaStdLibs "org.ballerinalang:crypto-ballerina:${stdlibCryptoVersion}" ballerinaStdLibs "org.ballerinalang:log-ballerina:${stdlibLogVersion}" ballerinaStdLibs "org.ballerinalang:stringutils-ballerina:${stdlibStringUtilsVersion}" ballerinaStdLibs "org.ballerinalang:time-ballerina:${stdlibTimeVersion}" // Transitive dependencies - ballerinaStdLibs "org.ballerinalang:config-ballerina:${stdlibConfigVersion}" - ballerinaStdLibs "org.ballerinalang:io-ballerina:${stdlibIoVersion}" ballerinaStdLibs "org.ballerinalang:runtime-ballerina:${stdlibRuntimeVersion}" - ballerinaStdLibs "org.ballerinalang:system-ballerina:${stdlibSystemVersion}" ballerinaStdLibs "org.ballerinalang:task-ballerina:${stdlibTaskVersion}" } } diff --git a/gradle.properties b/gradle.properties index 635f02db..77bf8541 100644 --- a/gradle.properties +++ b/gradle.properties @@ -2,15 +2,11 @@ org.gradle.caching=true group=org.ballerinalang version=1.0.4-SNAPSHOT ballerinaLangVersion=2.0.0-Preview8-SNAPSHOT -stdlibAuthVersion=1.0.4-SNAPSHOT stdlibCacheVersion=2.0.4-SNAPSHOT stdlibCryptoVersion=1.0.4-SNAPSHOT stdlibLogVersion=1.0.4-SNAPSHOT stdlibStringUtilsVersion=0.5.4-SNAPSHOT stdlibTimeVersion=1.0.5-SNAPSHOT # Transitive dependencies -stdlibConfigVersion=1.0.4-SNAPSHOT -stdlibIoVersion=0.5.4-SNAPSHOT stdlibRuntimeVersion=0.5.4-SNAPSHOT -stdlibSystemVersion=0.6.4-SNAPSHOT stdlibTaskVersion=1.1.4-SNAPSHOT diff --git a/oauth2-ballerina/Ballerina.toml b/oauth2-ballerina/Ballerina.toml index 771b6b34..796d5047 100644 --- a/oauth2-ballerina/Ballerina.toml +++ b/oauth2-ballerina/Ballerina.toml @@ -3,11 +3,6 @@ org = "ballerina" name = "oauth2" version = "@toml.version@" -[[dependency]] -org = "ballerina" -name = "auth" -version = "@stdlib.auth.version@" - [[dependency]] org = "ballerina" name = "cache" diff --git a/oauth2-ballerina/build.gradle b/oauth2-ballerina/build.gradle index 47390e46..35f1e85d 100644 --- a/oauth2-ballerina/build.gradle +++ b/oauth2-ballerina/build.gradle @@ -86,7 +86,6 @@ def originalConfig = ballerinaConfigFile.text task updateTomlVersions { doLast { - def stdlibDependentAuthVersion = project.stdlibAuthVersion.split("-")[0] def stdlibDependentCacheVersion = project.stdlibCacheVersion.split("-")[0] def stdlibDependentCryptoVersion = project.stdlibCryptoVersion.split("-")[0] def stdlibDependentLogVersion = project.stdlibLogVersion.split("-")[0] @@ -95,7 +94,6 @@ task updateTomlVersions { def newConfig = ballerinaConfigFile.text.replace("@project.version@", project.version) newConfig = newConfig.replace("@toml.version@", tomlVersion) - newConfig = newConfig.replace("@stdlib.auth.version@", stdlibDependentAuthVersion) newConfig = newConfig.replace("@stdlib.cache.version@", stdlibDependentCacheVersion) newConfig = newConfig.replace("@stdlib.crypto.version@", stdlibDependentCryptoVersion) newConfig = newConfig.replace("@stdlib.log.version@", stdlibDependentLogVersion) From 63ca16708860e4305fa9ac67a6c6f34c929a5439 Mon Sep 17 00:00:00 2001 From: Chanaka Lakmal Date: Thu, 17 Dec 2020 20:25:34 +0530 Subject: [PATCH 7/9] Refactor code --- oauth2-ballerina/oauth2_errors.bal | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/oauth2-ballerina/oauth2_errors.bal b/oauth2-ballerina/oauth2_errors.bal index 2ce762d6..a5e2356b 100644 --- a/oauth2-ballerina/oauth2_errors.bal +++ b/oauth2-ballerina/oauth2_errors.bal @@ -22,18 +22,11 @@ public type OAuth2Error distinct error; # Represents the OAuth2 error. public type Error OAuth2Error; -# Logs and prepares the `error` as an `oauth2:Error`. -# -# + message - Error message -# + err - `error` instance -# + return - Prepared `oauth2:Error` instance +// Logs and prepares the `error` as an `oauth2:Error`. isolated function prepareError(string message, error? err = ()) returns Error { log:printError(message, err = err); - Error oauth2Error; if (err is error) { - oauth2Error = OAuth2Error(message, err); - } else { - oauth2Error = OAuth2Error(message); + return OAuth2Error(message, err); } - return oauth2Error; + return OAuth2Error(message); } From 48cff69e6495a12f82f254dccd1775250c7626c8 Mon Sep 17 00:00:00 2001 From: Chanaka Lakmal Date: Wed, 23 Dec 2020 09:59:40 +0530 Subject: [PATCH 8/9] Refactor code --- .../stdlib/oauth2/OAuth2Client.java | 30 +++++++++---------- .../{Constants.java => OAuth2Constants.java} | 2 +- 2 files changed, 16 insertions(+), 16 deletions(-) rename oauth2-native/src/main/java/org/ballerinalang/stdlib/oauth2/{Constants.java => OAuth2Constants.java} (98%) diff --git a/oauth2-native/src/main/java/org/ballerinalang/stdlib/oauth2/OAuth2Client.java b/oauth2-native/src/main/java/org/ballerinalang/stdlib/oauth2/OAuth2Client.java index c3f6fbcc..d5a3d8b8 100644 --- a/oauth2-native/src/main/java/org/ballerinalang/stdlib/oauth2/OAuth2Client.java +++ b/oauth2-native/src/main/java/org/ballerinalang/stdlib/oauth2/OAuth2Client.java @@ -53,7 +53,7 @@ public class OAuth2Client { public static Object doHttpRequest(BString url, BMap clientConfig, BMap headers, BString payload) { - String customPayload = getStringValueIfPresent(clientConfig, Constants.CUSTOM_PAYLOAD); + String customPayload = getStringValueIfPresent(clientConfig, OAuth2Constants.CUSTOM_PAYLOAD); String textPayload = payload.getValue(); if (customPayload != null) { textPayload += "&" + customPayload; @@ -66,7 +66,7 @@ public static Object doHttpRequest(BString url, BMap clientConf } BMap customHeaders = - (BMap) getMapValueIfPresent(clientConfig, Constants.CUSTOM_HEADERS); + (BMap) getMapValueIfPresent(clientConfig, OAuth2Constants.CUSTOM_HEADERS); if (customHeaders != null) { for (Map.Entry entry : customHeaders.entrySet()) { headersList.add(entry.getKey().getValue()); @@ -82,11 +82,11 @@ public static Object doHttpRequest(BString url, BMap clientConf request = buildHttpRequest(url.getValue(), flatHeaders, textPayload); } - String httpVersion = getStringValueIfPresent(clientConfig, Constants.HTTP_VERSION); + String httpVersion = getStringValueIfPresent(clientConfig, OAuth2Constants.HTTP_VERSION); BMap secureSocket = - (BMap) getMapValueIfPresent(clientConfig, Constants.SECURE_SOCKET); + (BMap) getMapValueIfPresent(clientConfig, OAuth2Constants.SECURE_SOCKET); if (secureSocket != null) { - boolean disable = secureSocket.getBooleanValue(StringUtils.fromString(Constants.DISABLE)); + boolean disable = secureSocket.getBooleanValue(StringUtils.fromString(OAuth2Constants.DISABLE)); if (disable) { try { SSLContext sslContext = initSslContext(); @@ -97,7 +97,7 @@ public static Object doHttpRequest(BString url, BMap clientConf } } BMap trustStore = - (BMap) getMapValueIfPresent(secureSocket, Constants.TRUSTSTORE); + (BMap) getMapValueIfPresent(secureSocket, OAuth2Constants.TRUSTSTORE); if (trustStore != null) { try { SSLContext sslContext = initSslContext(trustStore); @@ -113,7 +113,7 @@ public static Object doHttpRequest(BString url, BMap clientConf } private static HttpClient.Version getHttpVersion(String httpVersion) { - if (Constants.HTTP_2.equals(httpVersion)) { + if (OAuth2Constants.HTTP_2.equals(httpVersion)) { return HttpClient.Version.HTTP_2; } return HttpClient.Version.HTTP_1_1; @@ -133,21 +133,21 @@ public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; - SSLContext sslContext = SSLContext.getInstance(Constants.TLS); + SSLContext sslContext = SSLContext.getInstance(OAuth2Constants.TLS); sslContext.init(null, trustAllCerts, new SecureRandom()); return sslContext; } private static SSLContext initSslContext(BMap trustStore) throws Exception { - String path = trustStore.getStringValue(StringUtils.fromString(Constants.PATH)).getValue(); - String password = trustStore.getStringValue(StringUtils.fromString(Constants.PASSWORD)).getValue(); + String path = trustStore.getStringValue(StringUtils.fromString(OAuth2Constants.PATH)).getValue(); + String password = trustStore.getStringValue(StringUtils.fromString(OAuth2Constants.PASSWORD)).getValue(); InputStream is = new FileInputStream(new File(path)); char[] passphrase = password.toCharArray(); - KeyStore ks = KeyStore.getInstance(Constants.PKCS12); + KeyStore ks = KeyStore.getInstance(OAuth2Constants.PKCS12); ks.load(is, passphrase); TrustManagerFactory tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); tmf.init(ks); - SSLContext sslContext = SSLContext.getInstance(Constants.TLS); + SSLContext sslContext = SSLContext.getInstance(OAuth2Constants.TLS); sslContext.init(null, tmf.getTrustManagers(), new SecureRandom()); return sslContext; } @@ -163,7 +163,7 @@ private static HttpClient buildHttpClient(String httpVersion, SSLContext sslCont private static HttpRequest buildHttpRequest(String url, String payload) { return HttpRequest.newBuilder() .uri(URI.create(url)) - .setHeader(Constants.CONTENT_TYPE, Constants.APPLICATION_FORM_URLENCODED) + .setHeader(OAuth2Constants.CONTENT_TYPE, OAuth2Constants.APPLICATION_FORM_URLENCODED) .POST(HttpRequest.BodyPublishers.ofString(payload)) .build(); } @@ -172,7 +172,7 @@ private static HttpRequest buildHttpRequest(String url, String[] headers, String return HttpRequest.newBuilder() .uri(URI.create(url)) .headers(headers) - .setHeader(Constants.CONTENT_TYPE, Constants.APPLICATION_FORM_URLENCODED) + .setHeader(OAuth2Constants.CONTENT_TYPE, OAuth2Constants.APPLICATION_FORM_URLENCODED) .POST(HttpRequest.BodyPublishers.ofString(payload)) .build(); } @@ -201,7 +201,7 @@ private static String getStringValueIfPresent(BMap config, Stri } private static BError createError(String errMsg) { - return ErrorCreator.createDistinctError(Constants.OAUTH2_ERROR_TYPE, ModuleUtils.getModule(), + return ErrorCreator.createDistinctError(OAuth2Constants.OAUTH2_ERROR_TYPE, ModuleUtils.getModule(), StringUtils.fromString(errMsg)); } } diff --git a/oauth2-native/src/main/java/org/ballerinalang/stdlib/oauth2/Constants.java b/oauth2-native/src/main/java/org/ballerinalang/stdlib/oauth2/OAuth2Constants.java similarity index 98% rename from oauth2-native/src/main/java/org/ballerinalang/stdlib/oauth2/Constants.java rename to oauth2-native/src/main/java/org/ballerinalang/stdlib/oauth2/OAuth2Constants.java index 81ea7505..68ce83e7 100644 --- a/oauth2-native/src/main/java/org/ballerinalang/stdlib/oauth2/Constants.java +++ b/oauth2-native/src/main/java/org/ballerinalang/stdlib/oauth2/OAuth2Constants.java @@ -21,7 +21,7 @@ /** * Constants related to Ballerina OAuth2 stdlib. */ -public class Constants { +public class OAuth2Constants { public static final String OAUTH2_ERROR_TYPE = "OAuth2Error"; public static final String HTTP_VERSION = "httpVersion"; From cba0d51fd605a6c8554b21a2d7ccd21ac22104ed Mon Sep 17 00:00:00 2001 From: Chanaka Lakmal Date: Wed, 23 Dec 2020 22:33:16 +0530 Subject: [PATCH 9/9] Remove issue template --- issue_template.md | 18 ------------------ 1 file changed, 18 deletions(-) delete mode 100644 issue_template.md diff --git a/issue_template.md b/issue_template.md deleted file mode 100644 index 757e13ef..00000000 --- a/issue_template.md +++ /dev/null @@ -1,18 +0,0 @@ -**Description:** - - -**Suggested Labels:** - - -**Suggested Assignees:** - - -**Affected Product Version:** - -**OS, DB, other environment details and versions:** - -**Steps to reproduce:** - - -**Related Issues:** - \ No newline at end of file