-
Notifications
You must be signed in to change notification settings - Fork 623
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
Add SSO feature for Store application #4316
Merged
Merged
Changes from 22 commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
d95126a
sso feature initial commit
npamudika b435e31
Add SSO feature - get Authorization Code changes
npamudika c4df213
SSO feature - Add Callback microservice
npamudika cffbeb1
Add SSO feature callback changes
npamudika f8cb146
Add SSO feature - access token retrieval
npamudika 6ae15f3
Add SSO feature - Redirection and Configuration changes
npamudika be8b4ef
Add SSO Login feature changes
npamudika 7ed6f11
Revert unwanted commit
npamudika 100a465
Revert unwanted changes
npamudika c56dceb
Revert commit changes
npamudika 0aca22f
Review fixes
npamudika 1f8eadc
Review fixes
npamudika 2043226
Review fixes
npamudika 15d506e
Add AuthenticatorService, Move SSO related code to react authenticator
npamudika da20943
Remove duplicate classes of SSO
npamudika 012ecc8
Review fixes
npamudika 67b0122
Review fixes
npamudika 303faba
Add AuthenticatorService tests
npamudika 1ef198b
Refactor code
npamudika 6ac4344
AuthentictorService tests
npamudika 5f4b896
Review fixes - DBScriptRunnerUtil class
npamudika a12ccb4
Review fixes - Constants
npamudika 8e9f128
Review fixes - Throw exceptions
npamudika 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 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
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
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 |
---|---|---|
|
@@ -15,27 +15,40 @@ | |
* specific language governing permissions and limitations | ||
* under the License. | ||
*/ | ||
|
||
package org.wso2.carbon.apimgt.rest.api.authenticator; | ||
|
||
import com.google.gson.JsonObject; | ||
import org.apache.commons.lang3.StringUtils; | ||
import org.osgi.service.component.annotations.Component; | ||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
import org.wso2.carbon.apimgt.core.api.KeyManager; | ||
import org.wso2.carbon.apimgt.core.exception.APIManagementException; | ||
import org.wso2.carbon.apimgt.core.exception.ExceptionCodes; | ||
import org.wso2.carbon.apimgt.core.impl.APIManagerFactory; | ||
import org.wso2.carbon.apimgt.core.models.AccessTokenInfo; | ||
import org.wso2.carbon.apimgt.core.util.KeyManagerConstants; | ||
import org.wso2.carbon.apimgt.rest.api.authenticator.configuration.models.APIMStoreConfigurations; | ||
import org.wso2.carbon.apimgt.rest.api.authenticator.constants.AuthenticatorConstants; | ||
import org.wso2.carbon.apimgt.rest.api.authenticator.dto.ErrorDTO; | ||
import org.wso2.carbon.apimgt.rest.api.authenticator.internal.ServiceReferenceHolder; | ||
import org.wso2.carbon.apimgt.rest.api.authenticator.utils.AuthUtil; | ||
import org.wso2.carbon.apimgt.rest.api.authenticator.utils.bean.AuthResponseBean; | ||
import org.wso2.carbon.apimgt.core.exception.APIManagementException; | ||
import org.wso2.carbon.apimgt.core.exception.ExceptionCodes; | ||
import org.wso2.carbon.apimgt.rest.api.common.APIConstants; | ||
import org.wso2.msf4j.Microservice; | ||
import org.wso2.msf4j.Request; | ||
import org.wso2.msf4j.formparam.FormDataParam; | ||
|
||
import java.net.URI; | ||
import java.net.URISyntaxException; | ||
import javax.ws.rs.Consumes; | ||
import javax.ws.rs.GET; | ||
import javax.ws.rs.POST; | ||
import javax.ws.rs.Path; | ||
import javax.ws.rs.Produces; | ||
import javax.ws.rs.core.Context; | ||
import javax.ws.rs.core.HttpHeaders; | ||
import javax.ws.rs.core.MediaType; | ||
import javax.ws.rs.core.NewCookie; | ||
import javax.ws.rs.core.Response; | ||
|
@@ -44,7 +57,6 @@ | |
* This class provides access token during login from store app. | ||
* | ||
*/ | ||
|
||
@Component( | ||
name = "org.wso2.carbon.apimgt.rest.api.authenticator.AuthenticatorAPI", | ||
service = Microservice.class, | ||
|
@@ -68,12 +80,15 @@ public Response authenticate(@Context Request request, @FormDataParam ("username | |
@FormDataParam ("validity_period") String validityPeriod, | ||
@FormDataParam ("remember_me") boolean isRememberMe, @FormDataParam ("scopes") String scopesList) { | ||
try { | ||
LoginTokenService loginTokenService = new LoginTokenService(); | ||
KeyManager keyManager = APIManagerFactory.getInstance().getKeyManager(); | ||
AuthenticatorService authenticatorService = new AuthenticatorService(keyManager); | ||
AuthResponseBean authResponseBean = new AuthResponseBean(); | ||
String appContext = AuthUtil.getAppContext(request); | ||
String restAPIContext; | ||
if (appContext.contains("editor") || request.getUri().contains("publisher")) { | ||
restAPIContext = AuthenticatorConstants.REST_CONTEXT + "/publisher"; | ||
if (appContext.contains(AuthenticatorConstants.EDITOR_APPLICATION) || | ||
request.getUri().contains(AuthenticatorConstants.PUBLISHER_APPLICATION)) { | ||
restAPIContext = AuthenticatorConstants.REST_CONTEXT + "/" + | ||
AuthenticatorConstants.PUBLISHER_APPLICATION; | ||
} else { | ||
restAPIContext = AuthenticatorConstants.REST_CONTEXT + appContext; | ||
} | ||
|
@@ -88,14 +103,12 @@ public Response authenticate(@Context Request request, @FormDataParam ("username | |
return Response.status(Response.Status.UNAUTHORIZED).entity(errorDTO).build(); | ||
} | ||
} | ||
String tokens = loginTokenService | ||
.getTokens(authResponseBean, appContext.substring(1), userName, password, grantType, refToken, | ||
Long.parseLong(validityPeriod)); | ||
String accessToken = tokens.split(":")[0]; | ||
String refreshToken = null; | ||
if (tokens.split(":").length > 1) { | ||
refreshToken = tokens.split(":")[1]; | ||
} | ||
AccessTokenInfo accessTokenInfo = authenticatorService.getTokens(appContext.substring(1), | ||
null, grantType, userName, password, refToken, | ||
Long.parseLong(validityPeriod)); | ||
authenticatorService.setAccessTokenData(authResponseBean, accessTokenInfo); | ||
String accessToken = accessTokenInfo.getAccessToken(); | ||
String refreshToken = accessTokenInfo.getRefreshToken(); | ||
|
||
// The access token is stored as two cookies in client side. One is a normal cookie and other is a http | ||
// only cookie. Hence we need to split the access token | ||
|
@@ -110,7 +123,7 @@ public Response authenticate(@Context Request request, @FormDataParam ("username | |
.cookieBuilder(APIConstants.AccessTokenConstants.AM_TOKEN_MSF4J, part2, restAPIContext, true, true, | ||
""); | ||
NewCookie refreshTokenCookie, refreshTokenHttpOnlyCookie; | ||
// refresh token is not set to cookie if remember me is not set. | ||
// Refresh token is not set to cookie if remember me is not set. | ||
if (refreshToken != null && (AuthenticatorConstants.REFRESH_GRANT.equals(grantType) || ( | ||
AuthenticatorConstants.PASSWORD_GRANT.equals(grantType) && isRememberMe))) { | ||
String refTokenPart1 = refreshToken.substring(0, refreshToken.length() / 2); | ||
|
@@ -146,31 +159,30 @@ public Response authenticate(@Context Request request, @FormDataParam ("username | |
"").build(); | ||
} | ||
} catch (APIManagementException e) { | ||
|
||
ErrorDTO errorDTO = AuthUtil.getErrorDTO(e.getErrorHandler(), null); | ||
|
||
log.error(e.getMessage(), e); | ||
return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build(); | ||
} | ||
} | ||
|
||
@POST | ||
@Produces (MediaType.APPLICATION_JSON) | ||
@Path ("/revoke") | ||
@Path ("/logout") | ||
public Response logout(@Context Request request) { | ||
String appContext = AuthUtil.getAppContext(request); | ||
String restAPIContext; | ||
if (appContext.contains("editor")) { | ||
restAPIContext = AuthenticatorConstants.REST_CONTEXT + "/publisher"; | ||
if (appContext.contains(AuthenticatorConstants.EDITOR_APPLICATION)) { | ||
restAPIContext = AuthenticatorConstants.REST_CONTEXT + "/" + AuthenticatorConstants.PUBLISHER_APPLICATION; | ||
} else { | ||
restAPIContext = AuthenticatorConstants.REST_CONTEXT + appContext; | ||
} | ||
String accessToken = AuthUtil | ||
.extractTokenFromHeaders(request.getHeaders(), AuthenticatorConstants.ACCESS_TOKEN_2); | ||
if (accessToken != null) { | ||
try { | ||
LoginTokenService loginTokenService = new LoginTokenService(); | ||
loginTokenService.revokeAccessToken(appContext.substring(1), accessToken); | ||
KeyManager keyManager = APIManagerFactory.getInstance().getKeyManager(); | ||
AuthenticatorService authenticatorService = new AuthenticatorService(keyManager); | ||
authenticatorService.revokeAccessToken(appContext.substring(1), accessToken); | ||
// Lets invalidate all the cookies saved. | ||
NewCookie appContextCookie = AuthUtil | ||
.cookieBuilder(AuthenticatorConstants.ACCESS_TOKEN_2, "", appContext, true, true, | ||
|
@@ -196,7 +208,108 @@ public Response logout(@Context Request request) { | |
errorDTO.setCode(ExceptionCodes.INVALID_AUTHORIZATION_HEADER.getErrorCode()); | ||
errorDTO.setMessage(ExceptionCodes.INVALID_AUTHORIZATION_HEADER.getErrorMessage()); | ||
return Response.status(Response.Status.UNAUTHORIZED).entity(errorDTO).build(); | ||
} | ||
|
||
/** | ||
* This method provides the DCR application information to the SSO-IS login. | ||
* | ||
* @param request Request to call the /login api | ||
* @return Response - Response object with OAuth data | ||
*/ | ||
@GET | ||
@Path("/login/{appName}") | ||
@Produces(MediaType.APPLICATION_JSON) | ||
public Response redirect(@Context Request request) { | ||
String appContext = AuthUtil.getAppContext(request); | ||
String appName = appContext.substring(1); | ||
try { | ||
KeyManager keyManager = APIManagerFactory.getInstance().getKeyManager(); | ||
AuthenticatorService authenticatorService = new AuthenticatorService(keyManager); | ||
JsonObject oAuthData = authenticatorService.getAuthenticationConfigurations(appName); | ||
if (oAuthData.size() == 0) { | ||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR) | ||
.entity("Error while creating the OAuth application!").build(); | ||
} else { | ||
return Response.status(Response.Status.OK).entity(oAuthData).build(); | ||
} | ||
} catch (APIManagementException e) { | ||
ErrorDTO errorDTO = AuthUtil.getErrorDTO(e.getErrorHandler(), null); | ||
log.error(e.getMessage(), e); | ||
return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build(); | ||
} | ||
} | ||
|
||
/** | ||
* This is the API which IDP redirects the user after authentication. | ||
* | ||
* @param request Request to call /callback api | ||
* @return Response - Response with redirect URL | ||
*/ | ||
@GET | ||
@Path("/callback/{appName}") | ||
@Produces(MediaType.APPLICATION_JSON) | ||
public Response callback(@Context Request request) { | ||
String appContext = AuthUtil.getAppContext(request).split("\\?")[0]; | ||
String appName = appContext.substring(1); | ||
String restAPIContext; | ||
if (appContext.contains(AuthenticatorConstants.EDITOR_APPLICATION) || | ||
request.getUri().contains(AuthenticatorConstants.PUBLISHER_APPLICATION)) { | ||
restAPIContext = AuthenticatorConstants.REST_CONTEXT + "/" + AuthenticatorConstants.PUBLISHER_APPLICATION; | ||
} else { | ||
restAPIContext = AuthenticatorConstants.REST_CONTEXT + appContext; | ||
} | ||
String requestURL = (String) request.getProperty("REQUEST_URL"); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. move to a constant |
||
|
||
APIMStoreConfigurations storeConfigs = ServiceReferenceHolder.getInstance().getAPIMStoreConfiguration(); | ||
AuthResponseBean authResponseBean = new AuthResponseBean(); | ||
String grantType = KeyManagerConstants.AUTHORIZATION_CODE_GRANT_TYPE; | ||
try { | ||
KeyManager keyManager = APIManagerFactory.getInstance().getKeyManager(); | ||
AuthenticatorService authenticatorService = new AuthenticatorService(keyManager); | ||
AccessTokenInfo accessTokenInfo = authenticatorService.getTokens(appName, requestURL, grantType, | ||
null, null, null, 0); | ||
if (StringUtils.isEmpty(accessTokenInfo.toString())) { | ||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR) | ||
.entity("Access token generation failed!").build(); | ||
} else { | ||
authenticatorService.setAccessTokenData(authResponseBean, accessTokenInfo); | ||
String accessToken = accessTokenInfo.getAccessToken(); | ||
if (log.isDebugEnabled()) { | ||
log.debug("Received access token for " + appName + " application."); | ||
} | ||
// Set Access Token cookies | ||
String part1 = accessToken.substring(0, accessToken.length() / 2); | ||
String part2 = accessToken.substring(accessToken.length() / 2); | ||
NewCookie cookieWithAppContext = AuthUtil | ||
.cookieBuilder(AuthenticatorConstants.ACCESS_TOKEN_1, part1, appContext, | ||
true, false, "future"); | ||
NewCookie httpOnlyCookieWithAppContext = AuthUtil | ||
.cookieBuilder(AuthenticatorConstants.ACCESS_TOKEN_2, part2, appContext, | ||
true, true, "future"); | ||
NewCookie restAPIContextCookie = AuthUtil | ||
.cookieBuilder(APIConstants.AccessTokenConstants.AM_TOKEN_MSF4J, part2, restAPIContext, | ||
true, true, "future"); | ||
String authUser = authResponseBean.getAuthUser(); | ||
NewCookie authUserCookie = AuthUtil | ||
.cookieBuilder(AuthenticatorConstants.AUTH_USER, authUser, appContext, true, false, ""); | ||
if (log.isDebugEnabled()) { | ||
log.debug("Set cookies for " + appName + " application."); | ||
} | ||
// Redirect to the store/apis page (redirect URL) | ||
URI targetURIForRedirection = new URI(storeConfigs.getApimBaseUrl() + appName); | ||
return Response.status(Response.Status.FOUND) | ||
.header(HttpHeaders.LOCATION, targetURIForRedirection).entity(authResponseBean) | ||
.cookie(cookieWithAppContext, httpOnlyCookieWithAppContext, | ||
restAPIContextCookie, authUserCookie) | ||
.build(); | ||
} | ||
} catch (APIManagementException e) { | ||
ErrorDTO errorDTO = AuthUtil.getErrorDTO(e.getErrorHandler(), null); | ||
log.error(e.getMessage(), e); | ||
return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build(); | ||
} catch (URISyntaxException e) { | ||
log.error(e.getMessage(), e); | ||
return Response.status(e.getIndex()).build(); | ||
} | ||
} | ||
} |
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.
I don't think we can compare application contexts in this manner since they can change. Please create a Github issue for this, we need to fix it properly in all places.
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.
Github issue created at,
#4319 [C5][Authenticator] Compare application contexts