You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@knox.apache.org by mo...@apache.org on 2017/09/01 13:17:09 UTC
[11/64] [partial] knox git commit: KNOX-998 - Refactoring save 1
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/deploy/JWTFederationContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/deploy/JWTFederationContributor.java b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/deploy/JWTFederationContributor.java
new file mode 100644
index 0000000..47e8f0f
--- /dev/null
+++ b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/deploy/JWTFederationContributor.java
@@ -0,0 +1,63 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.knox.gateway.provider.federation.jwt.deploy;
+
+import org.apache.knox.gateway.deploy.DeploymentContext;
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributorBase;
+import org.apache.knox.gateway.descriptor.FilterParamDescriptor;
+import org.apache.knox.gateway.descriptor.ResourceDescriptor;
+import org.apache.knox.gateway.topology.Provider;
+import org.apache.knox.gateway.topology.Service;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+public class JWTFederationContributor extends
+ ProviderDeploymentContributorBase {
+
+ private static final String FILTER_CLASSNAME = "JWTFederationFilter";
+
+ @Override
+ public String getRole() {
+ return "federation";
+ }
+
+ @Override
+ public String getName() {
+ return "JWTProvider";
+ }
+
+ @Override
+ public void contributeProvider( DeploymentContext context, Provider provider ) {
+ }
+
+ @Override
+ public void contributeFilter( DeploymentContext context, Provider provider, Service service, ResourceDescriptor resource, List<FilterParamDescriptor> params ) {
+ // blindly add all the provider params as filter init params
+ if (params == null) {
+ params = new ArrayList<FilterParamDescriptor>();
+ }
+ Map<String, String> providerParams = provider.getParams();
+ for(Entry<String, String> entry : providerParams.entrySet()) {
+ params.add( resource.createFilterParam().name( entry.getKey().toLowerCase() ).value( entry.getValue() ) );
+ }
+ resource.addFilter().name( getName() ).role( getRole() ).impl( FILTER_CLASSNAME ).params( params );
+ }
+}
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/deploy/SSOCookieFederationContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/deploy/SSOCookieFederationContributor.java b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/deploy/SSOCookieFederationContributor.java
new file mode 100644
index 0000000..f798236
--- /dev/null
+++ b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/deploy/SSOCookieFederationContributor.java
@@ -0,0 +1,63 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.knox.gateway.provider.federation.jwt.deploy;
+
+import org.apache.knox.gateway.deploy.DeploymentContext;
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributorBase;
+import org.apache.knox.gateway.descriptor.FilterParamDescriptor;
+import org.apache.knox.gateway.descriptor.ResourceDescriptor;
+import org.apache.knox.gateway.topology.Provider;
+import org.apache.knox.gateway.topology.Service;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+public class SSOCookieFederationContributor extends
+ ProviderDeploymentContributorBase {
+
+ private static final String FILTER_CLASSNAME = "SSOCookieFederationFilter";
+
+ @Override
+ public String getRole() {
+ return "federation";
+ }
+
+ @Override
+ public String getName() {
+ return "SSOCookieProvider";
+ }
+
+ @Override
+ public void contributeProvider( DeploymentContext context, Provider provider ) {
+ }
+
+ @Override
+ public void contributeFilter( DeploymentContext context, Provider provider, Service service, ResourceDescriptor resource, List<FilterParamDescriptor> params ) {
+ // blindly add all the provider params as filter init params
+ if (params == null) {
+ params = new ArrayList<FilterParamDescriptor>();
+ }
+ Map<String, String> providerParams = provider.getParams();
+ for(Entry<String, String> entry : providerParams.entrySet()) {
+ params.add( resource.createFilterParam().name( entry.getKey().toLowerCase() ).value( entry.getValue() ) );
+ }
+ resource.addFilter().name( getName() ).role( getRole() ).impl( FILTER_CLASSNAME ).params( params );
+ }
+}
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/AbstractJWTFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/AbstractJWTFilter.java b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/AbstractJWTFilter.java
new file mode 100644
index 0000000..ea64b45
--- /dev/null
+++ b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/AbstractJWTFilter.java
@@ -0,0 +1,263 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.knox.gateway.provider.federation.jwt.filter;
+
+import java.io.IOException;
+import java.security.Principal;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+import java.security.interfaces.RSAPublicKey;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import javax.security.auth.Subject;
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletContext;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.knox.gateway.audit.api.Action;
+import org.apache.knox.gateway.audit.api.ActionOutcome;
+import org.apache.knox.gateway.audit.api.AuditContext;
+import org.apache.knox.gateway.audit.api.AuditService;
+import org.apache.knox.gateway.audit.api.AuditServiceFactory;
+import org.apache.knox.gateway.audit.api.Auditor;
+import org.apache.knox.gateway.audit.api.ResourceType;
+import org.apache.knox.gateway.audit.log4j.audit.AuditConstants;
+import org.apache.knox.gateway.filter.AbstractGatewayFilter;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.provider.federation.jwt.JWTMessages;
+import org.apache.knox.gateway.security.PrimaryPrincipal;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.security.token.JWTokenAuthority;
+import org.apache.knox.gateway.services.security.token.TokenServiceException;
+import org.apache.knox.gateway.services.security.token.impl.JWTToken;
+
+/**
+ *
+ */
+public abstract class AbstractJWTFilter implements Filter {
+ static JWTMessages log = MessagesFactory.get( JWTMessages.class );
+ protected List<String> audiences;
+ protected JWTokenAuthority authority;
+ protected String verificationPEM = null;
+ protected RSAPublicKey publicKey = null;
+ private static AuditService auditService = AuditServiceFactory.getAuditService();
+ private static Auditor auditor = auditService.getAuditor(
+ AuditConstants.DEFAULT_AUDITOR_NAME, AuditConstants.KNOX_SERVICE_NAME,
+ AuditConstants.KNOX_COMPONENT_NAME );
+
+ public abstract void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+ throws IOException, ServletException;
+
+ /**
+ *
+ */
+ public AbstractJWTFilter() {
+ super();
+ }
+
+ @Override
+ public void init( FilterConfig filterConfig ) throws ServletException {
+ ServletContext context = filterConfig.getServletContext();
+ if (context != null) {
+ GatewayServices services = (GatewayServices) context.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
+ if (services != null) {
+ authority = (JWTokenAuthority) services.getService(GatewayServices.TOKEN_SERVICE);
+ }
+ }
+ }
+
+ /**
+ * @param expectedAudiences
+ * @return
+ */
+ protected List<String> parseExpectedAudiences(String expectedAudiences) {
+ ArrayList<String> audList = null;
+ // setup the list of valid audiences for token validation
+ if (expectedAudiences != null) {
+ // parse into the list
+ String[] audArray = expectedAudiences.split(",");
+ audList = new ArrayList<String>();
+ for (String a : audArray) {
+ audList.add(a);
+ }
+ }
+ return audList;
+ }
+
+ protected boolean tokenIsStillValid(JWTToken jwtToken) {
+ // if there is no expiration date then the lifecycle is tied entirely to
+ // the cookie validity - otherwise ensure that the current time is before
+ // the designated expiration time
+ Date expires = jwtToken.getExpiresDate();
+ return (expires == null || expires != null && new Date().before(expires));
+ }
+
+ /**
+ * Validate whether any of the accepted audience claims is present in the
+ * issued token claims list for audience. Override this method in subclasses
+ * in order to customize the audience validation behavior.
+ *
+ * @param jwtToken
+ * the JWT token where the allowed audiences will be found
+ * @return true if an expected audience is present, otherwise false
+ */
+ protected boolean validateAudiences(JWTToken jwtToken) {
+ boolean valid = false;
+
+ String[] tokenAudienceList = jwtToken.getAudienceClaims();
+ // if there were no expected audiences configured then just
+ // consider any audience acceptable
+ if (audiences == null) {
+ valid = true;
+ } else {
+ // if any of the configured audiences is found then consider it
+ // acceptable
+ if (tokenAudienceList != null) {
+ for (String aud : tokenAudienceList) {
+ if (audiences.contains(aud)) {
+ log.jwtAudienceValidated();
+ valid = true;
+ break;
+ }
+ }
+ }
+ }
+ return valid;
+ }
+
+ protected void continueWithEstablishedSecurityContext(Subject subject, final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) throws IOException, ServletException {
+ Principal principal = (Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0];
+ AuditContext context = auditService.getContext();
+ if (context != null) {
+ context.setUsername( principal.getName() );
+ String sourceUri = (String)request.getAttribute( AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME );
+ if (sourceUri != null) {
+ auditor.audit( Action.AUTHENTICATION , sourceUri, ResourceType.URI, ActionOutcome.SUCCESS );
+ }
+ }
+
+ try {
+ Subject.doAs(
+ subject,
+ new PrivilegedExceptionAction<Object>() {
+ @Override
+ public Object run() throws Exception {
+ chain.doFilter(request, response);
+ return null;
+ }
+ }
+ );
+ }
+ catch (PrivilegedActionException e) {
+ Throwable t = e.getCause();
+ if (t instanceof IOException) {
+ throw (IOException) t;
+ }
+ else if (t instanceof ServletException) {
+ throw (ServletException) t;
+ }
+ else {
+ throw new ServletException(t);
+ }
+ }
+ }
+
+ protected Subject createSubjectFromToken(JWTToken token) {
+ final String principal = token.getSubject();
+
+ @SuppressWarnings("rawtypes")
+ HashSet emptySet = new HashSet();
+ Set<Principal> principals = new HashSet<>();
+ Principal p = new PrimaryPrincipal(principal);
+ principals.add(p);
+
+ // The newly constructed Sets check whether this Subject has been set read-only
+ // before permitting subsequent modifications. The newly created Sets also prevent
+ // illegal modifications by ensuring that callers have sufficient permissions.
+ //
+ // To modify the Principals Set, the caller must have AuthPermission("modifyPrincipals").
+ // To modify the public credential Set, the caller must have AuthPermission("modifyPublicCredentials").
+ // To modify the private credential Set, the caller must have AuthPermission("modifyPrivateCredentials").
+ javax.security.auth.Subject subject = new javax.security.auth.Subject(true, principals, emptySet, emptySet);
+ return subject;
+ }
+
+ protected boolean validateToken(HttpServletRequest request, HttpServletResponse response,
+ FilterChain chain, JWTToken token)
+ throws IOException, ServletException {
+ boolean verified = false;
+ try {
+ if (publicKey == null) {
+ verified = authority.verifyToken(token);
+ }
+ else {
+ verified = authority.verifyToken(token, publicKey);
+ }
+ } catch (TokenServiceException e) {
+ log.unableToVerifyToken(e);
+ }
+
+ if (verified) {
+ // confirm that issue matches intended target - which for this filter must be KNOXSSO
+ if (token.getIssuer().equals("KNOXSSO")) {
+ // if there is no expiration data then the lifecycle is tied entirely to
+ // the cookie validity - otherwise ensure that the current time is before
+ // the designated expiration time
+ if (tokenIsStillValid(token)) {
+ boolean audValid = validateAudiences(token);
+ if (audValid) {
+ return true;
+ }
+ else {
+ log.failedToValidateAudience();
+ handleValidationError(request, response, HttpServletResponse.SC_BAD_REQUEST,
+ "Bad request: missing required token audience");
+ }
+ }
+ else {
+ log.tokenHasExpired();
+ handleValidationError(request, response, HttpServletResponse.SC_BAD_REQUEST,
+ "Bad request: token has expired");
+ }
+ }
+ else {
+ handleValidationError(request, response, HttpServletResponse.SC_UNAUTHORIZED, null);
+ }
+ }
+ else {
+ log.failedToVerifyTokenSignature();
+ handleValidationError(request, response, HttpServletResponse.SC_UNAUTHORIZED, null);
+ }
+
+ return false;
+ }
+
+ protected abstract void handleValidationError(HttpServletRequest request, HttpServletResponse response, int status,
+ String error) throws IOException;
+
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/AccessTokenFederationFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/AccessTokenFederationFilter.java b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/AccessTokenFederationFilter.java
new file mode 100644
index 0000000..fcfee38
--- /dev/null
+++ b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/AccessTokenFederationFilter.java
@@ -0,0 +1,163 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.knox.gateway.provider.federation.jwt.filter;
+
+import java.io.IOException;
+import java.security.Principal;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+import java.text.ParseException;
+import java.util.HashSet;
+import java.util.Set;
+
+import javax.security.auth.Subject;
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.provider.federation.jwt.JWTMessages;
+import org.apache.knox.gateway.security.PrimaryPrincipal;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.security.token.JWTokenAuthority;
+import org.apache.knox.gateway.services.security.token.TokenServiceException;
+import org.apache.knox.gateway.services.security.token.impl.JWTToken;
+
+public class AccessTokenFederationFilter implements Filter {
+ private static JWTMessages log = MessagesFactory.get( JWTMessages.class );
+ private static final String BEARER = "Bearer ";
+
+ private JWTokenAuthority authority;
+
+ @Override
+ public void init( FilterConfig filterConfig ) throws ServletException {
+ GatewayServices services = (GatewayServices) filterConfig.getServletContext().getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
+ authority = (JWTokenAuthority) services.getService(GatewayServices.TOKEN_SERVICE);
+ }
+
+ public void destroy() {
+ }
+
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+ throws IOException, ServletException {
+ 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);
+ }
+
+ boolean verified = false;
+ try {
+ verified = authority.verifyToken(token);
+ } catch (TokenServiceException e) {
+ log.unableToVerifyToken(e);
+ }
+ if (verified) {
+ long expires = Long.parseLong(token.getExpires());
+ if (expires > System.currentTimeMillis()) {
+ if (((HttpServletRequest) request).getRequestURL().indexOf(token.getAudience().toLowerCase()) != -1) {
+ Subject subject = createSubjectFromToken(token);
+ continueWithEstablishedSecurityContext(subject, (HttpServletRequest)request, (HttpServletResponse)response, chain);
+ }
+ else {
+ log.failedToValidateAudience();
+ sendUnauthorized(response);
+ return; // break the chain
+ }
+ }
+ else {
+ log.tokenHasExpired();
+ sendUnauthorized(response);
+ return; // break the chain
+ }
+ }
+ else {
+ log.failedToVerifyTokenSignature();
+ sendUnauthorized(response);
+ return; // break the chain
+ }
+ }
+ else {
+ log.missingBearerToken();
+ sendUnauthorized(response);
+ return; // break the chain
+ }
+ }
+
+ private void sendUnauthorized(ServletResponse response) throws IOException {
+ ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
+ return;
+ }
+
+ private void continueWithEstablishedSecurityContext(Subject subject, final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) throws IOException, ServletException {
+ try {
+ Subject.doAs(
+ subject,
+ new PrivilegedExceptionAction<Object>() {
+ @Override
+ public Object run() throws Exception {
+ chain.doFilter(request, response);
+ return null;
+ }
+ }
+ );
+ }
+ catch (PrivilegedActionException e) {
+ Throwable t = e.getCause();
+ if (t instanceof IOException) {
+ throw (IOException) t;
+ }
+ else if (t instanceof ServletException) {
+ throw (ServletException) t;
+ }
+ else {
+ throw new ServletException(t);
+ }
+ }
+ }
+
+ private Subject createSubjectFromToken(JWTToken token) {
+ final String principal = token.getPrincipal();
+
+ HashSet emptySet = new HashSet();
+ Set<Principal> principals = new HashSet<>();
+ Principal p = new PrimaryPrincipal(principal);
+ principals.add(p);
+
+// The newly constructed Sets check whether this Subject has been set read-only
+// before permitting subsequent modifications. The newly created Sets also prevent
+// illegal modifications by ensuring that callers have sufficient permissions.
+//
+// To modify the Principals Set, the caller must have AuthPermission("modifyPrincipals").
+// To modify the public credential Set, the caller must have AuthPermission("modifyPublicCredentials").
+// To modify the private credential Set, the caller must have AuthPermission("modifyPrivateCredentials").
+ javax.security.auth.Subject subject = new javax.security.auth.Subject(true, principals, emptySet, emptySet);
+ return subject;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/JWTAccessTokenAssertionFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/JWTAccessTokenAssertionFilter.java b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/JWTAccessTokenAssertionFilter.java
new file mode 100644
index 0000000..f7e3725
--- /dev/null
+++ b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/JWTAccessTokenAssertionFilter.java
@@ -0,0 +1,164 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.knox.gateway.provider.federation.jwt.filter;
+
+import java.io.IOException;
+import java.security.AccessController;
+import java.security.Principal;
+import java.text.ParseException;
+import java.util.HashMap;
+
+import javax.security.auth.Subject;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.knox.gateway.filter.security.AbstractIdentityAssertionFilter;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.provider.federation.jwt.JWTMessages;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.registry.ServiceRegistry;
+import org.apache.knox.gateway.services.security.token.JWTokenAuthority;
+import org.apache.knox.gateway.services.security.token.TokenServiceException;
+import org.apache.knox.gateway.services.security.token.impl.JWTToken;
+import org.apache.knox.gateway.util.JsonUtils;
+
+public class JWTAccessTokenAssertionFilter extends AbstractIdentityAssertionFilter {
+ private static final String SVC_URL = "svc";
+ private static final String EXPIRES_IN = "expires_in";
+ private static final String TOKEN_TYPE = "token_type";
+ private static final String ACCESS_TOKEN = "access_token";
+ private static final String BEARER = "Bearer ";
+ private static JWTMessages log = MessagesFactory.get( JWTMessages.class );
+ private long validity;
+ private JWTokenAuthority authority = null;
+ private ServiceRegistry sr;
+
+ @Override
+ public void init( FilterConfig filterConfig ) throws ServletException {
+ super.init(filterConfig);
+ String validityStr = filterConfig.getInitParameter("validity");
+ if (validityStr == null) {
+ validityStr = "3600"; // 1 hr. in secs
+ }
+ validity = Long.parseLong(validityStr);
+
+ GatewayServices services = (GatewayServices) filterConfig.getServletContext().getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
+ authority = (JWTokenAuthority) services.getService(GatewayServices.TOKEN_SERVICE);
+ sr = (ServiceRegistry) services.getService(GatewayServices.SERVICE_REGISTRY_SERVICE);
+ }
+
+ @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);
+ //KNOX-685: response.getWriter().flush();
+ return; // break filter chain
+ }
+ 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);
+ return; //break filter chain
+ }
+ }
+
+ private String getAccessToken(final String principalName, String serviceName, long expires) {
+ String accessToken = null;
+
+ Principal p = new Principal() {
+
+ @Override
+ public String getName() {
+ // TODO Auto-generated method stub
+ return principalName;
+ }
+ };
+ JWTToken token = null;
+ try {
+ token = authority.issueToken(p, serviceName, "RS256", expires);
+ // Coverity CID 1327961
+ if( token != null ) {
+ accessToken = token.toString();
+ }
+ } catch (TokenServiceException e) {
+ log.unableToIssueToken(e);
+ }
+
+ return accessToken;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/JWTAuthCodeAssertionFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/JWTAuthCodeAssertionFilter.java b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/JWTAuthCodeAssertionFilter.java
new file mode 100644
index 0000000..32d0e99
--- /dev/null
+++ b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/JWTAuthCodeAssertionFilter.java
@@ -0,0 +1,100 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.knox.gateway.provider.federation.jwt.filter;
+
+import java.io.IOException;
+import java.security.AccessController;
+import java.util.HashMap;
+
+import javax.security.auth.Subject;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+
+import org.apache.knox.gateway.filter.security.AbstractIdentityAssertionFilter;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.registry.ServiceRegistry;
+import org.apache.knox.gateway.services.security.token.JWTokenAuthority;
+import org.apache.knox.gateway.services.security.token.TokenServiceException;
+import org.apache.knox.gateway.services.security.token.impl.JWTToken;
+import org.apache.knox.gateway.util.JsonUtils;
+
+public class JWTAuthCodeAssertionFilter extends AbstractIdentityAssertionFilter {
+ private static final String BEARER = "Bearer ";
+
+ private JWTokenAuthority authority = null;
+
+ private ServiceRegistry sr;
+
+ @Override
+ public void init( FilterConfig filterConfig ) throws ServletException {
+ super.init(filterConfig);
+ String validityStr = filterConfig.getInitParameter("validity");
+ if (validityStr == null) {
+ validityStr = "3600"; // 1 hr. in secs
+ }
+// validity = Long.parseLong(validityStr);
+
+ GatewayServices services = (GatewayServices) filterConfig.getServletContext().getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
+ authority = (JWTokenAuthority) services.getService(GatewayServices.TOKEN_SERVICE);
+ sr = (ServiceRegistry) services.getService(GatewayServices.SERVICE_REGISTRY_SERVICE);
+ }
+
+ @Override
+ public void doFilter(ServletRequest request, ServletResponse response,
+ FilterChain chain) throws IOException, ServletException {
+
+ Subject subject = Subject.getSubject(AccessController.getContext());
+ String principalName = getPrincipalName(subject);
+ principalName = mapper.mapUserPrincipal(principalName);
+ JWTToken authCode;
+ try {
+ authCode = authority.issueToken(subject, "RS256");
+ // get the url for the token service
+ String url = null;
+ if (sr != null) {
+ url = sr.lookupServiceURL("token", "TGS");
+ }
+
+ HashMap<String, Object> map = new HashMap<>();
+ // TODO: populate map from JWT authorization code
+ // Coverity CID 1327960
+ if( authCode != null ) {
+ map.put( "iss", authCode.getIssuer() );
+ map.put( "sub", authCode.getPrincipal() );
+ map.put( "aud", authCode.getAudience() );
+ map.put( "exp", authCode.getExpires() );
+ map.put( "code", authCode.toString() );
+ }
+ if (url != null) {
+ map.put("tke", url);
+ }
+
+ String jsonResponse = JsonUtils.renderAsJsonString(map);
+
+ response.getWriter().write(jsonResponse);
+ //KNOX-685: response.getWriter().flush();
+ } catch (TokenServiceException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ return; // break filter chain
+ }
+}
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/JWTFederationFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/JWTFederationFilter.java b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/JWTFederationFilter.java
new file mode 100644
index 0000000..3850502
--- /dev/null
+++ b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/JWTFederationFilter.java
@@ -0,0 +1,109 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.knox.gateway.provider.federation.jwt.filter;
+
+import org.apache.knox.gateway.services.security.token.impl.JWTToken;
+import org.apache.knox.gateway.util.CertificateUtils;
+
+import javax.security.auth.Subject;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import java.io.IOException;
+import java.text.ParseException;
+
+public class JWTFederationFilter extends AbstractJWTFilter {
+
+ public static final String KNOX_TOKEN_AUDIENCES = "knox.token.audiences";
+ public static final String TOKEN_VERIFICATION_PEM = "knox.token.verification.pem";
+ private static final String KNOX_TOKEN_QUERY_PARAM_NAME = "knox.token.query.param.name";
+ private static final String BEARER = "Bearer ";
+ private String paramName = "knoxtoken";
+
+ @Override
+ public void init( FilterConfig filterConfig ) throws ServletException {
+ super.init(filterConfig);
+
+ // expected audiences or null
+ String expectedAudiences = filterConfig.getInitParameter(KNOX_TOKEN_AUDIENCES);
+ if (expectedAudiences != null) {
+ audiences = parseExpectedAudiences(expectedAudiences);
+ }
+
+ // query param name for finding the provided knoxtoken
+ String queryParamName = filterConfig.getInitParameter(KNOX_TOKEN_QUERY_PARAM_NAME);
+ if (queryParamName != null) {
+ paramName = queryParamName;
+ }
+
+ // token verification pem
+ String verificationPEM = filterConfig.getInitParameter(TOKEN_VERIFICATION_PEM);
+ // setup the public key of the token issuer for verification
+ if (verificationPEM != null) {
+ publicKey = CertificateUtils.parseRSAPublicKey(verificationPEM);
+ }
+ }
+
+ public void destroy() {
+ }
+
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+ throws IOException, ServletException {
+ String header = ((HttpServletRequest) request).getHeader("Authorization");
+ String wireToken = null;
+ 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
+ wireToken = header.substring(BEARER.length());
+ }
+ else {
+ // check for query param
+ wireToken = ((HttpServletRequest) request).getParameter(paramName);
+ }
+
+ if (wireToken != null) {
+ try {
+ JWTToken token = new JWTToken(wireToken);
+ if (validateToken((HttpServletRequest)request, (HttpServletResponse)response, chain, token)) {
+ Subject subject = createSubjectFromToken(token);
+ continueWithEstablishedSecurityContext(subject, (HttpServletRequest)request, (HttpServletResponse)response, chain);
+ }
+ } catch (ParseException ex) {
+ ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
+ }
+ }
+ else {
+ // no token provided in header
+ ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
+ }
+ }
+
+ protected void handleValidationError(HttpServletRequest request, HttpServletResponse response, int status,
+ String error) throws IOException {
+ if (error != null) {
+ response.sendError(status, error);
+ }
+ else {
+ response.sendError(status);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/SSOCookieFederationFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/SSOCookieFederationFilter.java b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/SSOCookieFederationFilter.java
new file mode 100644
index 0000000..edfdc41
--- /dev/null
+++ b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/SSOCookieFederationFilter.java
@@ -0,0 +1,168 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.knox.gateway.provider.federation.jwt.filter;
+
+import java.io.IOException;
+import java.text.ParseException;
+
+import javax.security.auth.Subject;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.provider.federation.jwt.JWTMessages;
+import org.apache.knox.gateway.security.PrimaryPrincipal;
+import org.apache.knox.gateway.services.security.token.impl.JWTToken;
+import org.apache.knox.gateway.util.CertificateUtils;
+
+public class SSOCookieFederationFilter extends AbstractJWTFilter {
+ public static final String SSO_COOKIE_NAME = "sso.cookie.name";
+ public static final String SSO_EXPECTED_AUDIENCES = "sso.expected.audiences";
+ public static final String SSO_AUTHENTICATION_PROVIDER_URL = "sso.authentication.provider.url";
+ public static final String SSO_VERIFICATION_PEM = "sso.token.verification.pem";
+ private static JWTMessages log = MessagesFactory.get( JWTMessages.class );
+ private static final String ORIGINAL_URL_QUERY_PARAM = "originalUrl=";
+ private static final String DEFAULT_SSO_COOKIE_NAME = "hadoop-jwt";
+
+ private String cookieName;
+ private String authenticationProviderUrl;
+
+ @Override
+ public void init( FilterConfig filterConfig ) throws ServletException {
+ super.init(filterConfig);
+
+ // configured cookieName
+ cookieName = filterConfig.getInitParameter(SSO_COOKIE_NAME);
+ if (cookieName == null) {
+ cookieName = DEFAULT_SSO_COOKIE_NAME;
+ }
+
+ // expected audiences or null
+ String expectedAudiences = filterConfig.getInitParameter(SSO_EXPECTED_AUDIENCES);
+ if (expectedAudiences != null) {
+ audiences = parseExpectedAudiences(expectedAudiences);
+ }
+
+ // url to SSO authentication provider
+ authenticationProviderUrl = filterConfig.getInitParameter(SSO_AUTHENTICATION_PROVIDER_URL);
+ if (authenticationProviderUrl == null) {
+ log.missingAuthenticationProviderUrlConfiguration();
+ throw new ServletException("Required authentication provider URL is missing.");
+ }
+
+ // token verification pem
+ String verificationPEM = filterConfig.getInitParameter(SSO_VERIFICATION_PEM);
+ // setup the public key of the token issuer for verification
+ if (verificationPEM != null) {
+ publicKey = CertificateUtils.parseRSAPublicKey(verificationPEM);
+ }
+ }
+
+ public void destroy() {
+ }
+
+ @Override
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+ throws IOException, ServletException {
+ String wireToken = null;
+ HttpServletRequest req = (HttpServletRequest) request;
+
+ String loginURL = constructLoginURL(req);
+ wireToken = getJWTFromCookie(req);
+ if (wireToken == null) {
+ if (req.getMethod().equals("OPTIONS")) {
+ // CORS preflight requests to determine allowed origins and related config
+ // must be able to continue without being redirected
+ Subject sub = new Subject();
+ sub.getPrincipals().add(new PrimaryPrincipal("anonymous"));
+ continueWithEstablishedSecurityContext(sub, req, (HttpServletResponse) response, chain);
+ }
+ log.sendRedirectToLoginURL(loginURL);
+ ((HttpServletResponse) response).sendRedirect(loginURL);
+ }
+ else {
+ try {
+ JWTToken token = new JWTToken(wireToken);
+ if (validateToken((HttpServletRequest)request, (HttpServletResponse)response, chain, token)) {
+ Subject subject = createSubjectFromToken(token);
+ continueWithEstablishedSecurityContext(subject, (HttpServletRequest)request, (HttpServletResponse)response, chain);
+ }
+ } catch (ParseException ex) {
+ ((HttpServletResponse) response).sendRedirect(loginURL);
+ }
+ }
+ }
+
+ protected void handleValidationError(HttpServletRequest request, HttpServletResponse response, int status,
+ String error) throws IOException {
+ String loginURL = constructLoginURL(request);
+ response.sendRedirect(loginURL);
+ }
+
+ /**
+ * Encapsulate the acquisition of the JWT token from HTTP cookies within the
+ * request.
+ *
+ * @param req servlet request to get the JWT token from
+ * @return serialized JWT token
+ */
+ protected String getJWTFromCookie(HttpServletRequest req) {
+ String serializedJWT = null;
+ Cookie[] cookies = req.getCookies();
+ if (cookies != null) {
+ for (Cookie cookie : cookies) {
+ if (cookieName.equals(cookie.getName())) {
+ log.cookieHasBeenFound(cookieName);
+ serializedJWT = cookie.getValue();
+ break;
+ }
+ }
+ }
+ return serializedJWT;
+ }
+
+ /**
+ * Create the URL to be used for authentication of the user in the absence of
+ * a JWT token within the incoming request.
+ *
+ * @param request for getting the original request URL
+ * @return url to use as login url for redirect
+ */
+ protected String constructLoginURL(HttpServletRequest request) {
+ String delimiter = "?";
+ if (authenticationProviderUrl.contains("?")) {
+ delimiter = "&";
+ }
+ String loginURL = authenticationProviderUrl + delimiter
+ + ORIGINAL_URL_QUERY_PARAM
+ + request.getRequestURL().append(getOriginalQueryString(request));
+ return loginURL;
+ }
+
+ private String getOriginalQueryString(HttpServletRequest request) {
+ String originalQueryString = request.getQueryString();
+ return (originalQueryString == null) ? "" : "?" + originalQueryString;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-security-jwt/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
deleted file mode 100644
index cd69d46..0000000
--- a/gateway-provider-security-jwt/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
+++ /dev/null
@@ -1,23 +0,0 @@
-##########################################################################
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-##########################################################################
-
-org.apache.hadoop.gateway.provider.federation.jwt.deploy.JWTFederationContributor
-org.apache.hadoop.gateway.provider.federation.jwt.deploy.JWTAccessTokenAssertionContributor
-org.apache.hadoop.gateway.provider.federation.jwt.deploy.JWTAuthCodeAssertionContributor
-org.apache.hadoop.gateway.provider.federation.jwt.deploy.AccessTokenFederationContributor
-org.apache.hadoop.gateway.provider.federation.jwt.deploy.SSOCookieFederationContributor
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-security-jwt/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
new file mode 100644
index 0000000..0176dd4
--- /dev/null
+++ b/gateway-provider-security-jwt/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
@@ -0,0 +1,23 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.provider.federation.jwt.deploy.JWTFederationContributor
+org.apache.knox.gateway.provider.federation.jwt.deploy.JWTAccessTokenAssertionContributor
+org.apache.knox.gateway.provider.federation.jwt.deploy.JWTAuthCodeAssertionContributor
+org.apache.knox.gateway.provider.federation.jwt.deploy.AccessTokenFederationContributor
+org.apache.knox.gateway.provider.federation.jwt.deploy.SSOCookieFederationContributor
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/test/java/org/apache/hadoop/gateway/provider/federation/AbstractJWTFilterTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/test/java/org/apache/hadoop/gateway/provider/federation/AbstractJWTFilterTest.java b/gateway-provider-security-jwt/src/test/java/org/apache/hadoop/gateway/provider/federation/AbstractJWTFilterTest.java
deleted file mode 100644
index 26d477f..0000000
--- a/gateway-provider-security-jwt/src/test/java/org/apache/hadoop/gateway/provider/federation/AbstractJWTFilterTest.java
+++ /dev/null
@@ -1,490 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.hadoop.gateway.provider.federation;
-
-import static org.junit.Assert.fail;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.security.AccessController;
-import java.security.KeyPair;
-import java.security.KeyPairGenerator;
-import java.security.NoSuchAlgorithmException;
-import java.security.Principal;
-import java.security.cert.Certificate;
-import java.security.interfaces.RSAPrivateKey;
-import java.security.interfaces.RSAPublicKey;
-import java.text.MessageFormat;
-import java.util.Enumeration;
-import java.util.List;
-import java.util.ArrayList;
-import java.util.Properties;
-import java.util.Date;
-import java.util.Set;
-
-import javax.security.auth.Subject;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.codec.binary.Base64;
-import org.apache.hadoop.gateway.provider.federation.jwt.filter.AbstractJWTFilter;
-import org.apache.hadoop.gateway.provider.federation.jwt.filter.SSOCookieFederationFilter;
-import org.apache.hadoop.gateway.security.PrimaryPrincipal;
-import org.apache.hadoop.gateway.services.security.impl.X509CertificateUtil;
-import org.apache.hadoop.gateway.services.security.token.JWTokenAuthority;
-import org.apache.hadoop.gateway.services.security.token.TokenServiceException;
-import org.apache.hadoop.gateway.services.security.token.impl.JWT;
-import org.apache.hadoop.gateway.services.security.token.impl.JWTToken;
-import org.easymock.EasyMock;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-import com.nimbusds.jose.*;
-import com.nimbusds.jwt.JWTClaimsSet;
-import com.nimbusds.jwt.SignedJWT;
-import com.nimbusds.jose.crypto.RSASSASigner;
-import com.nimbusds.jose.util.Base64URL;
-
-public abstract class AbstractJWTFilterTest {
- private static final String SERVICE_URL = "https://localhost:8888/resource";
- private static final String dnTemplate = "CN={0},OU=Test,O=Hadoop,L=Test,ST=Test,C=US";
-
- protected AbstractJWTFilter handler = null;
- protected RSAPublicKey publicKey = null;
- protected RSAPrivateKey privateKey = null;
- protected String pem = null;
-
- protected abstract void setTokenOnRequest(HttpServletRequest request, SignedJWT jwt);
- protected abstract void setGarbledTokenOnRequest(HttpServletRequest request, SignedJWT jwt);
- protected abstract String getAudienceProperty();
- protected abstract String getVerificationPemProperty();
-
- private String buildDistinguishedName(String hostname) {
- MessageFormat headerFormatter = new MessageFormat(dnTemplate);
- String[] paramArray = new String[1];
- paramArray[0] = hostname;
- String dn = headerFormatter.format(paramArray);
- return dn;
- }
-
- @Before
- public void setup() throws Exception, NoSuchAlgorithmException {
- KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
- kpg.initialize(2048);
- KeyPair KPair = kpg.generateKeyPair();
- String dn = buildDistinguishedName(InetAddress.getLocalHost().getHostName());
- Certificate cert = X509CertificateUtil.generateCertificate(dn, KPair, 365, "SHA1withRSA");
- byte[] data = cert.getEncoded();
- Base64 encoder = new Base64( 76, "\n".getBytes( "ASCII" ) );
- pem = new String(encoder.encodeToString( data ).getBytes( "ASCII" )).trim();
-
- publicKey = (RSAPublicKey) KPair.getPublic();
- privateKey = (RSAPrivateKey) KPair.getPrivate();
- }
-
- @After
- public void teardown() throws Exception {
- handler.destroy();
- }
-
- @Test
- public void testValidJWT() throws Exception {
- try {
- Properties props = getProperties();
- handler.init(new TestFilterConfig(props));
-
- SignedJWT jwt = getJWT("alice", new Date(new Date().getTime() + 5000), privateKey, props);
-
- HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
- setTokenOnRequest(request, jwt);
-
- EasyMock.expect(request.getRequestURL()).andReturn(
- new StringBuffer(SERVICE_URL)).anyTimes();
- EasyMock.expect(request.getQueryString()).andReturn(null);
- HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
- EasyMock.expect(response.encodeRedirectURL(SERVICE_URL)).andReturn(
- SERVICE_URL);
- EasyMock.replay(request);
-
- TestFilterChain chain = new TestFilterChain();
- handler.doFilter(request, response, chain);
- Assert.assertTrue("doFilterCalled should not be false.", chain.doFilterCalled == true);
- Set<PrimaryPrincipal> principals = chain.subject.getPrincipals(PrimaryPrincipal.class);
- Assert.assertTrue("No PrimaryPrincipal", principals.size() > 0);
- Assert.assertEquals("Not the expected principal", "alice", ((Principal)principals.toArray()[0]).getName());
- } catch (ServletException se) {
- fail("Should NOT have thrown a ServletException.");
- }
- }
-
- @Test
- public void testValidAudienceJWT() throws Exception {
- try {
- Properties props = getProperties();
- props.put(getAudienceProperty(), "bar");
- handler.init(new TestFilterConfig(props));
-
- SignedJWT jwt = getJWT("alice", new Date(new Date().getTime() + 5000), privateKey, props);
-
- HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
- setTokenOnRequest(request, jwt);
-
- EasyMock.expect(request.getRequestURL()).andReturn(
- new StringBuffer(SERVICE_URL)).anyTimes();
- EasyMock.expect(request.getQueryString()).andReturn(null);
- HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
- EasyMock.expect(response.encodeRedirectURL(SERVICE_URL)).andReturn(
- SERVICE_URL);
- EasyMock.replay(request);
-
- TestFilterChain chain = new TestFilterChain();
- handler.doFilter(request, response, chain);
- Assert.assertTrue("doFilterCalled should not be false.", chain.doFilterCalled == true);
- Set<PrimaryPrincipal> principals = chain.subject.getPrincipals(PrimaryPrincipal.class);
- Assert.assertTrue("No PrimaryPrincipal", principals.size() > 0);
- Assert.assertEquals("Not the expected principal", "alice", ((Principal)principals.toArray()[0]).getName());
- } catch (ServletException se) {
- fail("Should NOT have thrown a ServletException.");
- }
- }
-
- @Test
- public void testInvalidAudienceJWT() throws Exception {
- try {
- Properties props = getProperties();
- props.put(getAudienceProperty(), "foo");
- props.put("sso.authentication.provider.url", "https://localhost:8443/gateway/knoxsso/api/v1/websso");
-
- handler.init(new TestFilterConfig(props));
-
- SignedJWT jwt = getJWT("alice", new Date(new Date().getTime() + 5000), privateKey, props);
-
- HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
- setTokenOnRequest(request, jwt);
-
- EasyMock.expect(request.getRequestURL()).andReturn(
- new StringBuffer(SERVICE_URL)).anyTimes();
- EasyMock.expect(request.getQueryString()).andReturn(null);
- HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
- EasyMock.expect(response.encodeRedirectURL(SERVICE_URL)).andReturn(
- SERVICE_URL);
- EasyMock.replay(request);
-
- TestFilterChain chain = new TestFilterChain();
- handler.doFilter(request, response, chain);
- Assert.assertTrue("doFilterCalled should not be true.", chain.doFilterCalled == false);
- Assert.assertTrue("No Subject should be returned.", chain.subject == null);
- } catch (ServletException se) {
- fail("Should NOT have thrown a ServletException.");
- }
- }
-
- @Test
- public void testValidVerificationPEM() throws Exception {
- try {
- Properties props = getProperties();
-
-// System.out.println("+" + pem + "+");
-
- props.put(getAudienceProperty(), "bar");
- props.put("sso.authentication.provider.url", "https://localhost:8443/gateway/knoxsso/api/v1/websso");
- props.put(getVerificationPemProperty(), pem);
- handler.init(new TestFilterConfig(props));
-
- SignedJWT jwt = getJWT("alice", new Date(new Date().getTime() + 50000), privateKey, props);
-
- HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
- setTokenOnRequest(request, jwt);
-
- EasyMock.expect(request.getRequestURL()).andReturn(
- new StringBuffer(SERVICE_URL)).anyTimes();
- EasyMock.expect(request.getQueryString()).andReturn(null);
- HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
- EasyMock.expect(response.encodeRedirectURL(SERVICE_URL)).andReturn(
- SERVICE_URL);
- EasyMock.replay(request);
-
- TestFilterChain chain = new TestFilterChain();
- handler.doFilter(request, response, chain);
- Assert.assertTrue("doFilterCalled should not be false.", chain.doFilterCalled == true);
- Set<PrimaryPrincipal> principals = chain.subject.getPrincipals(PrimaryPrincipal.class);
- Assert.assertTrue("No PrimaryPrincipal", principals.size() > 0);
- Assert.assertEquals("Not the expected principal", "alice", ((Principal)principals.toArray()[0]).getName());
- } catch (ServletException se) {
- fail("Should NOT have thrown a ServletException.");
- }
- }
-
- @Test
- public void testExpiredJWT() throws Exception {
- try {
- Properties props = getProperties();
- handler.init(new TestFilterConfig(props));
-
- SignedJWT jwt = getJWT("alice", new Date(new Date().getTime() - 1000), privateKey, props);
-
- HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
- setTokenOnRequest(request, jwt);
-
- EasyMock.expect(request.getRequestURL()).andReturn(
- new StringBuffer(SERVICE_URL)).anyTimes();
- EasyMock.expect(request.getQueryString()).andReturn(null);
- HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
- EasyMock.expect(response.encodeRedirectURL(SERVICE_URL)).andReturn(
- SERVICE_URL);
- EasyMock.replay(request);
-
- TestFilterChain chain = new TestFilterChain();
- handler.doFilter(request, response, chain);
- Assert.assertTrue("doFilterCalled should not be false.", chain.doFilterCalled == false);
- Assert.assertTrue("No Subject should be returned.", chain.subject == null);
- } catch (ServletException se) {
- fail("Should NOT have thrown a ServletException.");
- }
- }
-
- @Test
- public void testValidJWTNoExpiration() throws Exception {
- try {
- Properties props = getProperties();
- handler.init(new TestFilterConfig(props));
-
- SignedJWT jwt = getJWT("alice", null, privateKey, props);
-
- HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
- setTokenOnRequest(request, jwt);
-
- EasyMock.expect(request.getRequestURL()).andReturn(
- new StringBuffer(SERVICE_URL)).anyTimes();
- EasyMock.expect(request.getQueryString()).andReturn(null);
- HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
- EasyMock.expect(response.encodeRedirectURL(SERVICE_URL)).andReturn(
- SERVICE_URL).anyTimes();
- EasyMock.replay(request);
-
- TestFilterChain chain = new TestFilterChain();
- handler.doFilter(request, response, chain);
- Assert.assertTrue("doFilterCalled should not be false.", chain.doFilterCalled == true);
- Set<PrimaryPrincipal> principals = chain.subject.getPrincipals(PrimaryPrincipal.class);
- Assert.assertTrue("No PrimaryPrincipal", principals.size() > 0);
- Assert.assertEquals("Not the expected principal", "alice", ((Principal)principals.toArray()[0]).getName());
- } catch (ServletException se) {
- fail("Should NOT have thrown a ServletException.");
- }
- }
-
- @Test
- public void testUnableToParseJWT() throws Exception {
- try {
- Properties props = getProperties();
- handler.init(new TestFilterConfig(props));
-
- SignedJWT jwt = getJWT("bob",new Date(new Date().getTime() + 5000), privateKey, props);
-
- HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
- setGarbledTokenOnRequest(request, jwt);
-
- EasyMock.expect(request.getRequestURL()).andReturn(
- new StringBuffer(SERVICE_URL)).anyTimes();
- EasyMock.expect(request.getQueryString()).andReturn(null);
- HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
- EasyMock.expect(response.encodeRedirectURL(SERVICE_URL)).andReturn(
- SERVICE_URL).anyTimes();
- EasyMock.replay(request);
-
- TestFilterChain chain = new TestFilterChain();
- handler.doFilter(request, response, chain);
- Assert.assertTrue("doFilterCalled should not be false.", chain.doFilterCalled == false);
- Assert.assertTrue("No Subject should be returned.", chain.subject == null);
- } catch (ServletException se) {
- fail("Should NOT have thrown a ServletException.");
- }
- }
-
- protected Properties getProperties() {
- Properties props = new Properties();
- props.setProperty(
- SSOCookieFederationFilter.SSO_AUTHENTICATION_PROVIDER_URL,
- "https://localhost:8443/authserver");
- return props;
- }
-
- protected SignedJWT getJWT(String sub, Date expires, RSAPrivateKey privateKey,
- Properties props) throws Exception {
- List<String> aud = new ArrayList<String>();
- aud.add("bar");
-
- JWTClaimsSet claims = new JWTClaimsSet.Builder()
- .issuer("KNOXSSO")
- .subject(sub)
- .audience(aud)
- .expirationTime(expires)
- .claim("scope", "openid")
- .build();
-
- JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).build();
-
- SignedJWT signedJWT = new SignedJWT(header, claims);
- Base64URL sigInput = Base64URL.encode(signedJWT.getSigningInput());
- JWSSigner signer = new RSASSASigner(privateKey);
-
- signedJWT.sign(signer);
-
- return signedJWT;
- }
-
- protected static class TestFilterConfig implements FilterConfig {
- Properties props = null;
-
- public TestFilterConfig(Properties props) {
- this.props = props;
- }
-
- @Override
- public String getFilterName() {
- return null;
- }
-
- /* (non-Javadoc)
- * @see javax.servlet.FilterConfig#getServletContext()
- */
- @Override
- public ServletContext getServletContext() {
-// JWTokenAuthority authority = EasyMock.createNiceMock(JWTokenAuthority.class);
-// GatewayServices services = EasyMock.createNiceMock(GatewayServices.class);
-// EasyMock.expect(services.getService("TokenService").andReturn(authority));
-// ServletContext context = EasyMock.createNiceMock(ServletContext.class);
-// EasyMock.expect(context.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE).andReturn(new DefaultGatewayServices()));
- return null;
- }
-
- /* (non-Javadoc)
- * @see javax.servlet.FilterConfig#getInitParameter(java.lang.String)
- */
- @Override
- public String getInitParameter(String name) {
- return props.getProperty(name, null);
- }
-
- /* (non-Javadoc)
- * @see javax.servlet.FilterConfig#getInitParameterNames()
- */
- @Override
- public Enumeration<String> getInitParameterNames() {
- return null;
- }
-
- }
-
- protected static class TestJWTokenAuthority implements JWTokenAuthority {
-
- /* (non-Javadoc)
- * @see org.apache.hadoop.gateway.services.security.token.JWTokenAuthority#issueToken(javax.security.auth.Subject, java.lang.String)
- */
- @Override
- public JWTToken issueToken(Subject subject, String algorithm)
- throws TokenServiceException {
- // TODO Auto-generated method stub
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.apache.hadoop.gateway.services.security.token.JWTokenAuthority#issueToken(java.security.Principal, java.lang.String)
- */
- @Override
- public JWTToken issueToken(Principal p, String algorithm)
- throws TokenServiceException {
- // TODO Auto-generated method stub
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.apache.hadoop.gateway.services.security.token.JWTokenAuthority#issueToken(java.security.Principal, java.lang.String, java.lang.String)
- */
- @Override
- public JWTToken issueToken(Principal p, String audience, String algorithm)
- throws TokenServiceException {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.apache.hadoop.gateway.services.security.token.JWTokenAuthority#verifyToken(org.apache.hadoop.gateway.services.security.token.impl.JWTToken)
- */
- @Override
- public boolean verifyToken(JWTToken token) throws TokenServiceException {
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.apache.hadoop.gateway.services.security.token.JWTokenAuthority#issueToken(java.security.Principal, java.lang.String, java.lang.String, long)
- */
- @Override
- public JWTToken issueToken(Principal p, String audience, String algorithm,
- long expires) throws TokenServiceException {
- return null;
- }
-
- @Override
- public JWTToken issueToken(Principal p, List<String> audiences, String algorithm,
- long expires) throws TokenServiceException {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.apache.hadoop.gateway.services.security.token.JWTokenAuthority#issueToken(java.security.Principal, java.lang.String, long)
- */
- @Override
- public JWT issueToken(Principal p, String audience, long l)
- throws TokenServiceException {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public boolean verifyToken(JWTToken token, RSAPublicKey publicKey) throws TokenServiceException {
- // TODO Auto-generated method stub
- return true;
- }
-
- }
-
- protected static class TestFilterChain implements FilterChain {
- boolean doFilterCalled = false;
- Subject subject = null;
-
- /* (non-Javadoc)
- * @see javax.servlet.FilterChain#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
- */
- @Override
- public void doFilter(ServletRequest request, ServletResponse response)
- throws IOException, ServletException {
- doFilterCalled = true;
-
- subject = Subject.getSubject( AccessController.getContext() );
- }
-
- }
-}
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/test/java/org/apache/hadoop/gateway/provider/federation/JWTFederationFilterTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/test/java/org/apache/hadoop/gateway/provider/federation/JWTFederationFilterTest.java b/gateway-provider-security-jwt/src/test/java/org/apache/hadoop/gateway/provider/federation/JWTFederationFilterTest.java
deleted file mode 100644
index 8d41423..0000000
--- a/gateway-provider-security-jwt/src/test/java/org/apache/hadoop/gateway/provider/federation/JWTFederationFilterTest.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.hadoop.gateway.provider.federation;
-
-import java.security.NoSuchAlgorithmException;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.apache.hadoop.gateway.provider.federation.jwt.filter.JWTFederationFilter;
-import org.apache.hadoop.gateway.services.security.token.JWTokenAuthority;
-import org.easymock.EasyMock;
-import org.junit.Before;
-
-import com.nimbusds.jwt.SignedJWT;
-
-public class JWTFederationFilterTest extends AbstractJWTFilterTest {
-
- @Before
- public void setup() throws Exception, NoSuchAlgorithmException {
- super.setup();
- handler = new TestJWTFederationFilter();
- ((TestJWTFederationFilter) handler).setTokenService(new TestJWTokenAuthority());
- }
-
- protected void setTokenOnRequest(HttpServletRequest request, SignedJWT jwt) {
- String token = "Bearer " + jwt.serialize();
- EasyMock.expect(request.getHeader("Authorization")).andReturn(token);
- }
-
- protected void setGarbledTokenOnRequest(HttpServletRequest request, SignedJWT jwt) {
- String token = "Bearer " + "ljm" + jwt.serialize();
- EasyMock.expect(request.getHeader("Authorization")).andReturn(token);
- }
-
- protected String getAudienceProperty() {
- return TestJWTFederationFilter.KNOX_TOKEN_AUDIENCES;
- }
-
- private static class TestJWTFederationFilter extends JWTFederationFilter {
-
- public void setTokenService(JWTokenAuthority ts) {
- authority = ts;
- }
-
- }
-
- @Override
- protected String getVerificationPemProperty() {
- return TestJWTFederationFilter.TOKEN_VERIFICATION_PEM;
- };
-
-}
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/test/java/org/apache/hadoop/gateway/provider/federation/JWTTokenTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/test/java/org/apache/hadoop/gateway/provider/federation/JWTTokenTest.java b/gateway-provider-security-jwt/src/test/java/org/apache/hadoop/gateway/provider/federation/JWTTokenTest.java
deleted file mode 100644
index 8d8bcab..0000000
--- a/gateway-provider-security-jwt/src/test/java/org/apache/hadoop/gateway/provider/federation/JWTTokenTest.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.hadoop.gateway.provider.federation;
-
-import java.util.ArrayList;
-import junit.framework.TestCase;
-
-import org.apache.hadoop.gateway.services.security.token.impl.JWTToken;
-import org.junit.Test;
-
-public class JWTTokenTest extends TestCase {
- private static final String JWT_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE0MTY5MjkxMDksImp0aSI6ImFhN2Y4ZDBhOTVjIiwic2NvcGVzIjpbInJlcG8iLCJwdWJsaWNfcmVwbyJdfQ.XCEwpBGvOLma4TCoh36FU7XhUbcskygS81HE1uHLf0E";
- private static final String HEADER = "{\"alg\":\"RS256\", \"type\":\"JWT\"}";
- private static final String CLAIMS = "{\"iss\": \"gateway\", \"prn\": \"john.doe@example.com\", \"aud\": \"https://login.example.com\", \"exp\": \"1363360913\"}";
-
-// public void testTokenParsing() throws Exception {
-// try {
-// JWTToken token = JWTToken.parseToken(JWT_TOKEN);
-// assertEquals(token.getHeader(), HEADER);
-// assertEquals(token.getClaims(), CLAIMS);
-//
-// assertEquals(token.getIssuer(), "gateway");
-// assertEquals(token.getPrincipal(), "john.doe@example.com");
-// assertEquals(token.getAudience(), "https://login.example.com");
-// assertEquals(token.getExpires(), "1363360913");
-// }
-// catch (ParseException pe) {
-// fail("ParseException encountered.");
-// }
-// }
-
- @Test
- public void testTokenCreation() throws Exception {
- String[] claims = new String[4];
- claims[0] = "KNOXSSO";
- claims[1] = "john.doe@example.com";
- claims[2] = "https://login.example.com";
- claims[3] = Long.toString( ( System.currentTimeMillis()/1000 ) + 300);
- JWTToken token = new JWTToken("RS256", claims);
-
- assertEquals("KNOXSSO", token.getIssuer());
- assertEquals("john.doe@example.com", token.getSubject());
- assertEquals("https://login.example.com", token.getAudience());
- }
-
- @Test
- public void testTokenCreationWithAudienceListSingle() throws Exception {
- String[] claims = new String[4];
- claims[0] = "KNOXSSO";
- claims[1] = "john.doe@example.com";
- claims[2] = null;
- claims[3] = Long.toString( ( System.currentTimeMillis()/1000 ) + 300);
- ArrayList<String> audiences = new ArrayList<String>();
- audiences.add("https://login.example.com");
-
- JWTToken token = new JWTToken("RS256", claims, audiences);
-
- assertEquals("KNOXSSO", token.getIssuer());
- assertEquals("john.doe@example.com", token.getSubject());
- assertEquals("https://login.example.com", token.getAudience());
- assertEquals(1, token.getAudienceClaims().length);
- }
-
- @Test
- public void testTokenCreationWithAudienceListMultiple() throws Exception {
- String[] claims = new String[4];
- claims[0] = "KNOXSSO";
- claims[1] = "john.doe@example.com";
- claims[2] = null;
- claims[3] = Long.toString( ( System.currentTimeMillis()/1000 ) + 300);
- ArrayList<String> audiences = new ArrayList<String>();
- audiences.add("https://login.example.com");
- audiences.add("KNOXSSO");
-
- JWTToken token = new JWTToken("RS256", claims, audiences);
-
- assertEquals("KNOXSSO", token.getIssuer());
- assertEquals("john.doe@example.com", token.getSubject());
- assertEquals("https://login.example.com", token.getAudience());
- assertEquals(2, token.getAudienceClaims().length);
- }
-
- @Test
- public void testTokenCreationWithAudienceListCombined() throws Exception {
- String[] claims = new String[4];
- claims[0] = "KNOXSSO";
- claims[1] = "john.doe@example.com";
- claims[2] = "LJM";
- claims[3] = Long.toString( ( System.currentTimeMillis()/1000 ) + 300);
- ArrayList<String> audiences = new ArrayList<String>();
- audiences.add("https://login.example.com");
- audiences.add("KNOXSSO");
-
- JWTToken token = new JWTToken("RS256", claims, audiences);
-
- assertEquals("KNOXSSO", token.getIssuer());
- assertEquals("john.doe@example.com", token.getSubject());
- assertEquals("https://login.example.com", token.getAudience());
- assertEquals(3, token.getAudienceClaims().length);
- }
-
- @Test
- public void testTokenCreationWithNullAudienceList() throws Exception {
- String[] claims = new String[4];
- claims[0] = "KNOXSSO";
- claims[1] = "john.doe@example.com";
- claims[2] = null;
- claims[3] = Long.toString( ( System.currentTimeMillis()/1000 ) + 300);
- ArrayList<String> audiences = null;
-
- JWTToken token = new JWTToken("RS256", claims, audiences);
-
- assertEquals("KNOXSSO", token.getIssuer());
- assertEquals("john.doe@example.com", token.getSubject());
- assertEquals(null, token.getAudience());
- assertEquals(null, token.getAudienceClaims());
- }
-}