use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project Kustvakt by KorAP.
the class OAuth2Controller method revokeAccessToken.
/**
* Revokes either an access token or a refresh token. Revoking a
* refresh token also revokes all access token associated with the
* refresh token.
*
* RFC 7009
* Client authentication for confidential client
*
* @param request
* @param form
* containing
* client_id,
* client_secret (required for confidential clients),
* token,
* token_type (optional)
* @return 200 if token invalidation is successful or the given
* token is invalid
*/
@POST
@Path("revoke")
@ResourceFilters({ APIVersionFilter.class })
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response revokeAccessToken(@Context HttpServletRequest request, MultivaluedMap<String, String> form) {
try {
OAuth2RevokeTokenRequest revokeTokenRequest = new OAuth2RevokeTokenRequest(new FormRequestWrapper(request, form));
tokenService.revokeToken(revokeTokenRequest);
return Response.ok("SUCCESS").build();
} catch (OAuthProblemException e) {
throw responseHandler.throwit(e);
} catch (OAuthSystemException e) {
throw responseHandler.throwit(e);
} catch (KustvaktException e) {
throw responseHandler.throwit(e);
}
}
use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project Kustvakt by KorAP.
the class OAuth2Controller method revokeTokenViaSuperClient.
@POST
@Path("revoke/super")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response revokeTokenViaSuperClient(@Context SecurityContext context, @Context HttpServletRequest request, MultivaluedMap<String, String> form) {
TokenContext tokenContext = (TokenContext) context.getUserPrincipal();
String username = tokenContext.getUsername();
try {
OAuth2RevokeTokenSuperRequest revokeTokenRequest = new OAuth2RevokeTokenSuperRequest(new FormRequestWrapper(request, form));
tokenService.revokeTokensViaSuperClient(username, revokeTokenRequest);
return Response.ok("SUCCESS").build();
} catch (OAuthSystemException e) {
throw responseHandler.throwit(e);
} catch (OAuthProblemException e) {
throw responseHandler.throwit(e);
} catch (KustvaktException e) {
throw responseHandler.throwit(e);
}
}
use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project Kustvakt by KorAP.
the class OAuth2Controller method requestAccessToken.
/**
* Grants a client an access token, namely a string used in
* authenticated requests representing user authorization for
* the client to access user resources. An additional refresh
* token strictly associated to the access token is also granted
* for confidential clients. Both public and confidential clients
* may issue multiple access tokens.
*
* <br /><br />
*
* Confidential clients may request refresh access token using
* this endpoint. This request will grant a new access token.
*
* Usually the given refresh token is not changed and can be used
* until it expires. However, currently there is a limitation of
* one access token per one refresh token. Thus, the given refresh
* token will be revoked, and a new access token and a new refresh
* token will be returned.
*
* <br /><br />
*
* Client credentials for authentication can be provided either as
* an authorization header with Basic authentication scheme or as
* form parameters in the request body.
*
* <br /><br />
*
* OAuth2 specification describes various ways of requesting an
* access token. Kustvakt supports:
* <ul>
* <li> Authorization code grant: obtains authorization from a
* third party application. Required parameters: grant_type,
* code, client_id, redirect_uri (if specified in the
* authorization request), client_secret (if the client is
* confidential or issued a secret).
* </li>
* <li> Resource owner password grant: strictly for clients that
* are parts of KorAP. Clients use user credentials, e.g. Kalamar
* (front-end) with login form. Required parameters: grant_type,
* username, password, client_id, client_secret (if the client is
* confidential or issued a secret). Optional parameters: scope.
* </li>
* <li> Client credentials grant: strictly for clients that are
* parts of KorAP. Clients access their own resources, not on
* behalf of a user. Required parameters: grant_type, client_id,
* client_secret. Optional parameters: scope.
* </li>
* </ul>
*
* RFC 6749: The value of the scope parameter is expressed as a
* list of space-delimited, case-sensitive strings defined by the
* authorization server.
*
* @param request
* the request
* @param form
* form parameters in a map
* @return a JSON object containing an access token, a refresh
* token, a token type and the token expiration in seconds
* if successful, an error code and an error description
* otherwise.
*/
@POST
@Path("token")
@ResourceFilters({ APIVersionFilter.class })
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public Response requestAccessToken(@Context HttpServletRequest request, @FormParam("grant_type") String grantType, MultivaluedMap<String, String> form) {
try {
boolean grantTypeExist = grantType != null && !grantType.isEmpty();
AbstractOAuthTokenRequest oAuthRequest = null;
if (grantTypeExist && grantType.equals(GrantType.CLIENT_CREDENTIALS.toString())) {
oAuthRequest = new OAuthTokenRequest(new FormRequestWrapper(request, form));
} else {
oAuthRequest = new OAuthUnauthenticatedTokenRequest(new FormRequestWrapper(request, form));
}
OAuthResponse oAuthResponse = tokenService.requestAccessToken(oAuthRequest);
return responseHandler.createResponse(oAuthResponse);
} catch (KustvaktException e) {
throw responseHandler.throwit(e);
} catch (OAuthProblemException e) {
throw responseHandler.throwit(e);
} catch (OAuthSystemException e) {
throw responseHandler.throwit(e);
}
}
use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project geoprism-registry by terraframe.
the class RegistrySessionService method ologin.
/**
* Serves as a "redirect url" for logging into DHIS2 via oauth.
*
* @param serverId
* @param code
* @param locales
* @param redirectBase
* @return
*/
@Authenticate
public static java.lang.String ologin(java.lang.String serverId, java.lang.String code, java.lang.String locales, java.lang.String redirectBase) {
try {
// We used to try to build this from the controller but it would include stuff (like the port :443) which then wouldn't match
// with the redirect url the client specified in DHIS2. Therefore this has to be something that the user can set (or, at least,
// in a properties file)
redirectBase = GeoregistryProperties.getRemoteServerUrl();
String redirect = redirectBase + "cgrsession/ologin";
OauthServer server = OauthServer.get(serverId);
/*
* Get the access token
*/
TokenRequestBuilder tokenBuilder = OAuthClientRequest.tokenLocation(server.getTokenLocation());
tokenBuilder.setGrantType(GrantType.AUTHORIZATION_CODE);
tokenBuilder.setRedirectURI(redirect);
tokenBuilder.setCode(code);
String auth = server.getClientId() + ":" + server.getSecretKey();
OAuthClientRequest tokenRequest = tokenBuilder.buildBodyMessage();
tokenRequest.setHeader("Accept", "application/json");
tokenRequest.setHeader("Authorization", "Basic " + new String(Base64.getEncoder().encode(auth.getBytes())));
URLConnectionClient connClient = new URLConnectionClient();
OAuthClient oAuthClient = new OAuthClient(connClient);
OAuthJSONAccessTokenResponse accessToken = oAuthClient.accessToken(tokenRequest, OAuth.HttpMethod.POST, OAuthJSONAccessTokenResponse.class);
/*
* Request the user information
*/
OAuthBearerClientRequest requestBuilder = new OAuthBearerClientRequest(server.getProfileLocation());
requestBuilder.setAccessToken(accessToken.getAccessToken());
OAuthClientRequest bearerRequest = requestBuilder.buildQueryMessage();
OAuthResourceResponse resourceResponse = oAuthClient.resource(bearerRequest, OAuth.HttpMethod.GET, OAuthResourceResponse.class);
String body = resourceResponse.getBody();
JSONObject object = new JSONObject(body);
final String username = object.getJSONObject("userCredentials").getString("username");
SingleActorDAOIF profile = RegistrySessionService.getActor(server, username);
String sessionId = SessionFacade.logIn(profile, LocaleSerializer.deserialize(locales));
JsonObject json = new JsonObject();
json.addProperty("sessionId", sessionId);
json.addProperty("username", username);
return json.toString();
} catch (JSONException | OAuthSystemException | OAuthProblemException e) {
throw new InvalidLoginException(e);
}
}
use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project entando-core by entando.
the class AuthEndpointServlet method doGet.
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
OAuthAuthzRequest oauthRequest = null;
OAuthIssuerImpl oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
IApiOAuthorizationCodeManager codeManager = (IApiOAuthorizationCodeManager) ApsWebApplicationUtils.getBean(SystemConstants.OAUTH2_AUTHORIZATION_CODE_MANAGER, request);
try {
oauthRequest = new OAuthAuthzRequest(request);
if (validateClient(oauthRequest, request, response)) {
// build response according to response_type
String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE) == null ? OAuth.OAUTH_RESPONSE_TYPE : oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);
OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse.authorizationResponse(request, HttpServletResponse.SC_FOUND);
final String authorizationCode = oauthIssuerImpl.authorizationCode();
final int expires = 3;
AuthorizationCode authCode = new AuthorizationCode();
authCode.setAuthorizationCode(authorizationCode);
// gets a calendar using the default time zone and locale.
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, expires);
authCode.setExpires(calendar.getTimeInMillis());
authCode.setClientId(oauthRequest.getClientId());
authCode.setSource(request.getRemoteAddr());
codeManager.addAuthorizationCode(authCode);
if (responseType.equals(ResponseType.CODE.toString())) {
builder.setCode(authorizationCode);
}
if (responseType.equals(ResponseType.TOKEN.toString())) {
builder.setAccessToken(authorizationCode);
builder.setExpiresIn((long) expires);
}
String redirectURI = oauthRequest.getParam(OAuth.OAUTH_REDIRECT_URI);
final OAuthResponse resp = builder.location(redirectURI).buildQueryMessage();
final int status = resp.getResponseStatus();
response.setStatus(status);
response.sendRedirect(resp.getLocationUri());
} else {
logger.warn("OAuth2 authentication failed");
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
}
} catch (OAuthSystemException ex) {
logger.error("System exception {} ", ex.getMessage());
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
} catch (OAuthProblemException ex) {
logger.error("OAuth2 error {} ", ex.getMessage());
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
} catch (IOException e) {
logger.error("IOException {} ", e);
}
}
Aggregations