use of org.apache.knox.gateway.services.security.token.TokenServiceException in project knox by apache.
the class TokenResource method getAuthenticationToken.
private Response getAuthenticationToken() {
if (clientCertRequired) {
X509Certificate cert = extractCertificate(request);
if (cert != null) {
if (!allowedDNs.contains(cert.getSubjectDN().getName())) {
return Response.status(403).entity("{ \"Unable to get token - untrusted client cert.\" }").build();
}
} else {
return Response.status(403).entity("{ \"Unable to get token - client cert required.\" }").build();
}
}
GatewayServices services = (GatewayServices) request.getServletContext().getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
JWTokenAuthority ts = services.getService(GatewayServices.TOKEN_SERVICE);
Principal p = ((HttpServletRequest) request).getUserPrincipal();
long expires = getExpiry();
try {
JWT token = null;
if (targetAudiences.isEmpty()) {
token = ts.issueToken(p, signatureAlgorithm, expires);
} else {
token = ts.issueToken(p, targetAudiences, signatureAlgorithm, expires);
}
if (token != null) {
String accessToken = token.toString();
HashMap<String, Object> map = new HashMap<>();
map.put(ACCESS_TOKEN, accessToken);
map.put(TOKEN_TYPE, BEARER);
map.put(EXPIRES_IN, expires);
if (tokenTargetUrl != null) {
map.put(TARGET_URL, tokenTargetUrl);
}
if (tokenClientDataMap != null) {
map.putAll(tokenClientDataMap);
}
String jsonResponse = JsonUtils.renderAsJsonString(map);
response.getWriter().write(jsonResponse);
return Response.ok().build();
} else {
return Response.serverError().build();
}
} catch (TokenServiceException | IOException e) {
log.unableToIssueToken(e);
}
return Response.ok().entity("{ \"Unable to acquire token.\" }").build();
}
use of org.apache.knox.gateway.services.security.token.TokenServiceException in project knox by apache.
the class WebSSOResource method getAuthenticationToken.
private Response getAuthenticationToken(int statusCode) {
GatewayServices services = (GatewayServices) request.getServletContext().getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
boolean removeOriginalUrlCookie = true;
String original = getCookieValue((HttpServletRequest) request, ORIGINAL_URL_COOKIE_NAME);
if (original == null) {
// in the case where there are no SAML redirects done before here
// we need to get it from the request parameters
removeOriginalUrlCookie = false;
original = getOriginalUrlFromQueryParams();
if (original.isEmpty()) {
log.originalURLNotFound();
throw new WebApplicationException("Original URL not found in the request.", Response.Status.BAD_REQUEST);
}
boolean validRedirect = RegExUtils.checkWhitelist(whitelist, original);
if (!validRedirect) {
log.whiteListMatchFail(original, whitelist);
throw new WebApplicationException("Original URL not valid according to the configured whitelist.", Response.Status.BAD_REQUEST);
}
}
JWTokenAuthority ts = services.getService(GatewayServices.TOKEN_SERVICE);
Principal p = ((HttpServletRequest) request).getUserPrincipal();
try {
JWT token = null;
if (targetAudiences.isEmpty()) {
token = ts.issueToken(p, signatureAlgorithm, getExpiry());
} else {
token = ts.issueToken(p, targetAudiences, signatureAlgorithm, getExpiry());
}
// Coverity CID 1327959
if (token != null) {
addJWTHadoopCookie(original, token);
}
if (removeOriginalUrlCookie) {
removeOriginalUrlCookie(response);
}
log.aboutToRedirectToOriginal(original);
response.setStatus(statusCode);
response.setHeader("Location", original);
try {
response.getOutputStream().close();
} catch (IOException e) {
log.unableToCloseOutputStream(e.getMessage(), Arrays.toString(e.getStackTrace()));
}
} catch (TokenServiceException e) {
log.unableToIssueToken(e);
}
URI location = null;
try {
location = new URI(original);
} catch (URISyntaxException urise) {
// todo log return error response
}
if (!enableSession) {
// invalidate the session to avoid autologin
// Coverity CID 1352857
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
}
}
return Response.seeOther(location).entity("{ \"redirectTo\" : " + original + " }").build();
}
use of org.apache.knox.gateway.services.security.token.TokenServiceException in project knox by apache.
the class DefaultTokenAuthorityService method issueToken.
@Override
public JWT issueToken(Principal p, List<String> audiences, String algorithm, long expires) throws TokenServiceException {
String[] claimArray = new String[4];
claimArray[0] = "KNOXSSO";
claimArray[1] = p.getName();
claimArray[2] = null;
if (expires == -1) {
claimArray[3] = null;
} else {
claimArray[3] = String.valueOf(expires);
}
JWT token = null;
if (SUPPORTED_SIG_ALGS.contains(algorithm)) {
token = new JWTToken(algorithm, claimArray, audiences);
RSAPrivateKey key;
char[] passphrase = null;
try {
passphrase = getSigningKeyPassphrase();
} catch (AliasServiceException e) {
throw new TokenServiceException(e);
}
try {
key = (RSAPrivateKey) ks.getSigningKey(getSigningKeyAlias(), passphrase);
JWSSigner signer = new RSASSASigner(key);
token.sign(signer);
} catch (KeystoreServiceException e) {
throw new TokenServiceException(e);
}
} else {
throw new TokenServiceException("Cannot issue token - Unsupported algorithm");
}
return token;
}
use of org.apache.knox.gateway.services.security.token.TokenServiceException in project knox by apache.
the class DefaultTokenAuthorityServiceTest method testTokenCreationBadSignatureAlgorithm.
@Test
public void testTokenCreationBadSignatureAlgorithm() throws Exception {
Principal principal = EasyMock.createNiceMock(Principal.class);
EasyMock.expect(principal.getName()).andReturn("john.doe@example.com");
GatewayConfig config = EasyMock.createNiceMock(GatewayConfig.class);
String basedir = System.getProperty("basedir");
if (basedir == null) {
basedir = new File(".").getCanonicalPath();
}
EasyMock.expect(config.getGatewaySecurityDir()).andReturn(basedir + "/target/test-classes");
EasyMock.expect(config.getSigningKeystoreName()).andReturn("server-keystore.jks");
EasyMock.expect(config.getSigningKeyAlias()).andReturn("server").anyTimes();
MasterService ms = EasyMock.createNiceMock(MasterService.class);
EasyMock.expect(ms.getMasterSecret()).andReturn("horton".toCharArray());
AliasService as = EasyMock.createNiceMock(AliasService.class);
EasyMock.expect(as.getGatewayIdentityPassphrase()).andReturn("horton".toCharArray());
EasyMock.replay(principal, config, ms, as);
KeystoreService ks = new DefaultKeystoreService();
((DefaultKeystoreService) ks).setMasterService(ms);
((DefaultKeystoreService) ks).init(config, new HashMap<String, String>());
JWTokenAuthority ta = new DefaultTokenAuthorityService();
((DefaultTokenAuthorityService) ta).setAliasService(as);
((DefaultTokenAuthorityService) ta).setKeystoreService(ks);
((DefaultTokenAuthorityService) ta).init(config, new HashMap<String, String>());
try {
ta.issueToken(principal, "none");
fail("Failure expected on a bad signature algorithm");
} catch (TokenServiceException ex) {
// expected
}
}
use of org.apache.knox.gateway.services.security.token.TokenServiceException in project knox by apache.
the class JWTAccessTokenAssertionFilter method doFilter.
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
String jsonResponse = null;
String header = ((HttpServletRequest) request).getHeader("Authorization");
if (header != null && header.startsWith(BEARER)) {
// what follows the bearer designator should be the JWT token being used to request or as an access token
String wireToken = header.substring(BEARER.length());
JWTToken token;
try {
token = JWTToken.parseToken(wireToken);
} catch (ParseException e) {
throw new ServletException("ParseException encountered while processing the JWT token: ", e);
}
// ensure that there is a valid jwt token available and that there isn't a misconfiguration of filters
if (token != null) {
try {
authority.verifyToken(token);
} catch (TokenServiceException e) {
log.unableToVerifyToken(e);
}
} else {
throw new ServletException("Expected JWT Token not provided as Bearer token");
}
// authorization of the user for the requested service (and resource?) should have been done by
// the JWTFederationFilter - once we get here we can assume that it is authorized and we just need
// to assert the identity via an access token
Subject subject = Subject.getSubject(AccessController.getContext());
String principalName = getPrincipalName(subject);
principalName = mapper.mapUserPrincipal(principalName);
// calculate expiration timestamp: validity * 1000 + currentTimeInMillis
long expires = System.currentTimeMillis() + validity * 1000;
String serviceName = request.getParameter("service-name");
String clusterName = request.getParameter("cluster-name");
String accessToken = getAccessToken(principalName, serviceName, expires);
String serviceURL = sr.lookupServiceURL(clusterName, serviceName);
HashMap<String, Object> map = new HashMap<>();
// TODO: populate map from JWT authorization code
map.put(ACCESS_TOKEN, accessToken);
map.put(TOKEN_TYPE, BEARER);
map.put(EXPIRES_IN, expires);
// TODO: this url needs to be rewritten when in gateway deployments....
map.put(SVC_URL, serviceURL);
jsonResponse = JsonUtils.renderAsJsonString(map);
response.getWriter().write(jsonResponse);
// break filter chain
return;
} else {
// no token provided in header
// something is really wrong since the JWTFederationFilter should have verified its existence already
// TODO: may have to check cookie and url as well before sending error
((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
// break filter chain
return;
}
}
Aggregations