You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@nifi.apache.org by mc...@apache.org on 2015/10/30 15:30:13 UTC
[47/50] [abbrv] nifi git commit: NIFI-655: - Refactoring web security
to use Spring Security Java Configuration. - Introducing security in Web UI
in order to get JWT.
http://git-wip-us.apache.org/repos/asf/nifi/blob/a40e5a07/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/pom.xml
----------------------------------------------------------------------
diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/pom.xml b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/pom.xml
index 59d81e1..c0db615 100644
--- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/pom.xml
+++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/pom.xml
@@ -22,6 +22,40 @@
</parent>
<groupId>org.apache.nifi</groupId>
<artifactId>nifi-web-security</artifactId>
+ <build>
+ <resources>
+ <resource>
+ <directory>src/main/resources</directory>
+ </resource>
+ <resource>
+ <directory>src/main/xsd</directory>
+ </resource>
+ </resources>
+ <plugins>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>jaxb2-maven-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>current</id>
+ <goals>
+ <goal>xjc</goal>
+ </goals>
+ <configuration>
+ <packageName>org.apache.nifi.authentication.generated</packageName>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <configuration>
+ <excludes>**/authentication/generated/*.java,</excludes>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
<dependencies>
<dependency>
<groupId>org.apache.nifi</groupId>
@@ -29,6 +63,10 @@
</dependency>
<dependency>
<groupId>org.apache.nifi</groupId>
+ <artifactId>nifi-nar-utils</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.nifi</groupId>
<artifactId>nifi-api</artifactId>
</dependency>
<dependency>
http://git-wip-us.apache.org/repos/asf/nifi/blob/a40e5a07/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/DnUtils.java
----------------------------------------------------------------------
diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/DnUtils.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/DnUtils.java
deleted file mode 100644
index f3bd11e..0000000
--- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/DnUtils.java
+++ /dev/null
@@ -1,85 +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.nifi.web.security;
-
-import java.security.cert.X509Certificate;
-import java.util.ArrayDeque;
-import java.util.Deque;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import javax.servlet.http.HttpServletRequest;
-import org.apache.nifi.web.security.x509.SubjectDnX509PrincipalExtractor;
-import org.apache.nifi.web.security.x509.X509CertificateExtractor;
-import org.apache.commons.lang3.StringUtils;
-
-/**
- *
- */
-public class DnUtils {
-
- private static final Pattern proxyChainPattern = Pattern.compile("<(.*?)>");
-
- /**
- * @param request http request
- * @return the X-ProxiedEntitiesChain from the specified request
- */
- public static String getXProxiedEntitiesChain(final HttpServletRequest request) {
- String xProxiedEntitiesChain = request.getHeader("X-ProxiedEntitiesChain");
- final X509Certificate cert = new X509CertificateExtractor().extractClientCertificate(request);
- if (cert != null) {
- final SubjectDnX509PrincipalExtractor principalExtractor = new SubjectDnX509PrincipalExtractor();
- final String extractedPrincipal = principalExtractor.extractPrincipal(cert).toString();
- final String formattedPrincipal = formatProxyDn(extractedPrincipal);
- if (StringUtils.isBlank(xProxiedEntitiesChain)) {
- xProxiedEntitiesChain = formattedPrincipal;
- } else {
- xProxiedEntitiesChain += formattedPrincipal;
- }
- }
-
- return xProxiedEntitiesChain;
- }
-
- /**
- * Formats the specified DN to be set as a HTTP header using well known
- * conventions.
- *
- * @param dn raw dn
- * @return the dn formatted as an HTTP header
- */
- public static String formatProxyDn(String dn) {
- return "<" + dn + ">";
- }
-
- /**
- * Tokenizes the specified proxy chain.
- *
- * @param rawProxyChain raw chain
- * @return tokenized proxy chain
- */
- public static Deque<String> tokenizeProxyChain(String rawProxyChain) {
- final Deque<String> dnList = new ArrayDeque<>();
-
- // parse the proxy chain
- final Matcher rawProxyChainMatcher = proxyChainPattern.matcher(rawProxyChain);
- while (rawProxyChainMatcher.find()) {
- dnList.push(rawProxyChainMatcher.group(1));
- }
-
- return dnList;
- }
-}
http://git-wip-us.apache.org/repos/asf/nifi/blob/a40e5a07/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/NiFiAuthenticationEntryPoint.java
----------------------------------------------------------------------
diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/NiFiAuthenticationEntryPoint.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/NiFiAuthenticationEntryPoint.java
new file mode 100644
index 0000000..6cae1f0
--- /dev/null
+++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/NiFiAuthenticationEntryPoint.java
@@ -0,0 +1,69 @@
+/*
+ * 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.nifi.web.security;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.web.AuthenticationEntryPoint;
+import org.springframework.security.web.WebAttributes;
+
+/**
+ * This is our own implementation of
+ * org.springframework.security.web.AuthenticationEntryPoint that allows us to
+ * send the response to the client exactly how we want to and log the results.
+ */
+public class NiFiAuthenticationEntryPoint implements AuthenticationEntryPoint {
+
+ private static final Logger logger = LoggerFactory.getLogger(NiFiAuthenticationEntryPoint.class);
+
+ /**
+ * Always returns a 403 error code to the client.
+ *
+ * @param request request
+ * @param response response
+ * @param ae ae
+ * @throws java.io.IOException ex
+ * @throws javax.servlet.ServletException ex
+ */
+ @Override
+ public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ae) throws IOException, ServletException {
+ // get the last exception - the exception that is being passed in is a generic no credentials found
+ // exception because the authentication could not be found in the security context. the actual cause
+ // of the problem is stored in the session as the authentication_exception
+ Object authenticationException = request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
+
+ // log request result
+ if (authenticationException instanceof AuthenticationException) {
+ ae = (AuthenticationException) authenticationException;
+ logger.info(String.format("Rejecting access to web api: %s", ae.getMessage()));
+ }
+
+ // set the response status
+ response.setStatus(HttpServletResponse.SC_FORBIDDEN);
+ response.setContentType("text/plain");
+
+ // write the response message
+ PrintWriter out = response.getWriter();
+ out.println("Access is denied.");
+ }
+}
http://git-wip-us.apache.org/repos/asf/nifi/blob/a40e5a07/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/NiFiAuthenticationFilter.java
----------------------------------------------------------------------
diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/NiFiAuthenticationFilter.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/NiFiAuthenticationFilter.java
new file mode 100644
index 0000000..b83b283
--- /dev/null
+++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/NiFiAuthenticationFilter.java
@@ -0,0 +1,136 @@
+/*
+ * 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.nifi.web.security;
+
+import java.io.IOException;
+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.commons.lang3.StringUtils;
+import org.apache.nifi.web.security.user.NiFiUserUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.security.authentication.AuthenticationManager;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.core.context.SecurityContextHolder;
+
+/**
+ *
+ */
+public abstract class NiFiAuthenticationFilter implements Filter {
+
+ private static final Logger logger = LoggerFactory.getLogger(NiFiAuthenticationFilter.class);
+
+ private AuthenticationManager authenticationManager;
+
+ @Override
+ public void init(final FilterConfig filterConfig) throws ServletException {
+ throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
+ }
+
+ @Override
+ public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Checking secure context token: " + SecurityContextHolder.getContext().getAuthentication());
+ }
+
+ if (requiresAuthentication((HttpServletRequest) request)) {
+ authenticate((HttpServletRequest) request, (HttpServletResponse) response);
+ }
+
+ chain.doFilter(request, response);
+ }
+
+ private boolean requiresAuthentication(final HttpServletRequest request) {
+ return NiFiUserUtils.getNiFiUser() == null && NiFiUserUtils.getNewAccountRequest() == null;
+ }
+
+ private void authenticate(final HttpServletRequest request, final HttpServletResponse response) {
+ try {
+ final Authentication authenticated = attemptAuthentication(request, response);
+ if (authenticated != null) {
+ final Authentication authorized = authenticationManager.authenticate(authenticated);
+ successfulAuthorization(request, response, authorized);
+ }
+ } catch (final AuthenticationException ae) {
+ unsuccessfulAuthorization(request, response, ae);
+ }
+ }
+
+ public abstract Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response);
+
+ protected void successfulAuthorization(HttpServletRequest request, HttpServletResponse response, Authentication authResult) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Authentication success: " + authResult);
+ }
+
+ SecurityContextHolder.getContext().setAuthentication(authResult);
+ ProxiedEntitiesUtils.successfulAuthorization(request, response, authResult);
+ }
+
+ protected void unsuccessfulAuthorization(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) {
+ ProxiedEntitiesUtils.unsuccessfulAuthorization(request, response, failed);
+ }
+
+ /**
+ * Determines if the specified request is attempting to register a new user account.
+ *
+ * @param request http request
+ * @return true if new user
+ */
+ protected final boolean isNewAccountRequest(HttpServletRequest request) {
+ if ("POST".equalsIgnoreCase(request.getMethod())) {
+ String path = request.getPathInfo();
+ if (StringUtils.isNotBlank(path)) {
+ if ("/controller/users".equals(path)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Extracts the justification from the specified request.
+ *
+ * @param request The request
+ * @return The justification
+ */
+ protected final String getJustification(HttpServletRequest request) {
+ // get the justification
+ String justification = request.getParameter("justification");
+ if (justification == null) {
+ justification = StringUtils.EMPTY;
+ }
+ return justification;
+ }
+
+ @Override
+ public void destroy() {
+ }
+
+ public void setAuthenticationManager(AuthenticationManager authenticationManager) {
+ this.authenticationManager = authenticationManager;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/nifi/blob/a40e5a07/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/NiFiAuthenticationProvider.java
----------------------------------------------------------------------
diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/NiFiAuthenticationProvider.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/NiFiAuthenticationProvider.java
new file mode 100644
index 0000000..e63a97e
--- /dev/null
+++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/NiFiAuthenticationProvider.java
@@ -0,0 +1,78 @@
+/*
+ * 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.nifi.web.security;
+
+import org.apache.nifi.web.security.token.NewAccountAuthenticationToken;
+import org.apache.nifi.web.security.token.NiFiAuthenticationRequestToken;
+import org.apache.nifi.web.security.token.NiFiAuthorizationToken;
+import org.springframework.security.authentication.AuthenticationProvider;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.core.userdetails.UsernameNotFoundException;
+
+/**
+ *
+ */
+public class NiFiAuthenticationProvider implements AuthenticationProvider {
+
+ private final AuthenticationProvider provider;
+ private final AuthenticationUserDetailsService<NiFiAuthenticationRequestToken> userDetailsService;
+
+ public NiFiAuthenticationProvider(final AuthenticationProvider provider, final AuthenticationUserDetailsService<NiFiAuthenticationRequestToken> userDetailsService) {
+ this.provider = provider;
+ this.userDetailsService = userDetailsService;
+ }
+
+ @Override
+ public Authentication authenticate(Authentication authentication) throws AuthenticationException {
+ final NiFiAuthenticationRequestToken request = (NiFiAuthenticationRequestToken) authentication;
+
+ // ensure the base provider could authenticate
+ final Authentication result = provider.authenticate(request);
+ if (result == null) {
+ return null;
+ }
+
+ try {
+ // defer to the nifi user details service to authorize the user
+ final UserDetails userDetails = userDetailsService.loadUserDetails(request);
+
+ // build an authentication for accesing nifi
+ return new NiFiAuthorizationToken(userDetails);
+ } catch (final UsernameNotFoundException unfe) {
+ // if the result was an authenticated new account request and it could not be authorized because the user was not found,
+ // return the token so the new account could be created. this must go here to ensure that any proxies have been authorized
+ if (isNewAccountAuthenticationToken(result)) {
+ return result;
+ } else {
+ throw unfe;
+ }
+ }
+ }
+
+ private boolean isNewAccountAuthenticationToken(final Authentication authentication) {
+ return NewAccountAuthenticationToken.class.isAssignableFrom(authentication.getClass());
+ }
+
+ @Override
+ public boolean supports(Class<?> authentication) {
+ return provider.supports(authentication) && NiFiAuthenticationRequestToken.class.isAssignableFrom(authentication);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/nifi/blob/a40e5a07/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/ProxiedEntitiesUtils.java
----------------------------------------------------------------------
diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/ProxiedEntitiesUtils.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/ProxiedEntitiesUtils.java
new file mode 100644
index 0000000..4526501
--- /dev/null
+++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/ProxiedEntitiesUtils.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.nifi.web.security;
+
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.apache.nifi.web.security.x509.SubjectDnX509PrincipalExtractor;
+import org.apache.nifi.web.security.x509.X509CertificateExtractor;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.nifi.user.NiFiUser;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+
+/**
+ *
+ */
+public class ProxiedEntitiesUtils {
+
+ public static final String PROXY_ENTITIES_CHAIN = "X-ProxiedEntitiesChain";
+ public static final String PROXY_ENTITIES_ACCEPTED = "X-ProxiedEntitiesAccepted";
+ public static final String PROXY_ENTITIES_DETAILS = "X-ProxiedEntitiesDetails";
+
+ private static final Pattern proxyChainPattern = Pattern.compile("<(.*?)>");
+
+ /**
+ * @param request http request
+ * @return the X-ProxiedEntitiesChain from the specified request
+ */
+ public static String getXProxiedEntitiesChain(final HttpServletRequest request) {
+ String xProxiedEntitiesChain = request.getHeader("X-ProxiedEntitiesChain");
+ final X509Certificate cert = new X509CertificateExtractor().extractClientCertificate(request);
+ if (cert != null) {
+ final SubjectDnX509PrincipalExtractor principalExtractor = new SubjectDnX509PrincipalExtractor();
+ final String extractedPrincipal = principalExtractor.extractPrincipal(cert).toString();
+ final String formattedPrincipal = formatProxyDn(extractedPrincipal);
+ if (StringUtils.isBlank(xProxiedEntitiesChain)) {
+ xProxiedEntitiesChain = formattedPrincipal;
+ } else {
+ xProxiedEntitiesChain += formattedPrincipal;
+ }
+ }
+
+ return xProxiedEntitiesChain;
+ }
+
+ /**
+ * Builds the dn chain for the specified user.
+ *
+ * @param user The current user
+ * @return The dn chain for that user
+ */
+ public static List<String> getXProxiedEntitiesChain(final NiFiUser user) {
+ // calculate the dn chain
+ final List<String> dnChain = new ArrayList<>();
+
+ // build the dn chain
+ NiFiUser chainedUser = user;
+ do {
+ // add the entry for this user
+ dnChain.add(chainedUser.getDn());
+
+ // go to the next user in the chain
+ chainedUser = chainedUser.getChain();
+ } while (chainedUser != null);
+
+ return dnChain;
+ }
+
+ /**
+ * Formats the specified DN to be set as a HTTP header using well known conventions.
+ *
+ * @param dn raw dn
+ * @return the dn formatted as an HTTP header
+ */
+ public static String formatProxyDn(String dn) {
+ return "<" + dn + ">";
+ }
+
+// /**
+// * Tokenizes the specified proxy chain.
+// *
+// * @param rawProxyChain raw chain
+// * @return tokenized proxy chain
+// */
+// public static Deque<String> tokenizeProxyChain(String rawProxyChain) {
+// final Deque<String> dnList = new ArrayDeque<>();
+//
+// // parse the proxy chain
+// final Matcher rawProxyChainMatcher = proxyChainPattern.matcher(rawProxyChain);
+// while (rawProxyChainMatcher.find()) {
+// dnList.push(rawProxyChainMatcher.group(1));
+// }
+//
+// return dnList;
+// }
+ public static List<String> buildProxyChain(final HttpServletRequest request, final String username) {
+ String principal;
+ if (username.startsWith("<") && username.endsWith(">")) {
+ principal = username;
+ } else {
+ principal = formatProxyDn(username);
+ }
+
+ // look for a proxied user
+ if (StringUtils.isNotBlank(request.getHeader(PROXY_ENTITIES_CHAIN))) {
+ principal = request.getHeader(PROXY_ENTITIES_CHAIN) + principal;
+ }
+
+ // parse the proxy chain
+ final List<String> proxyChain = new ArrayList<>();
+ final Matcher rawProxyChainMatcher = proxyChainPattern.matcher(principal);
+ while (rawProxyChainMatcher.find()) {
+ proxyChain.add(rawProxyChainMatcher.group(1));
+ }
+
+ return proxyChain;
+ }
+
+ public static String extractProxiedEntitiesChain(final HttpServletRequest request, final String username) {
+ String principal;
+ if (username.startsWith("<") && username.endsWith(">")) {
+ principal = username;
+ } else {
+ principal = formatProxyDn(username);
+ }
+
+ // look for a proxied user
+ if (StringUtils.isNotBlank(request.getHeader(PROXY_ENTITIES_CHAIN))) {
+ principal = request.getHeader(PROXY_ENTITIES_CHAIN) + principal;
+ }
+ return principal;
+ }
+
+ public static void successfulAuthorization(HttpServletRequest request, HttpServletResponse response, Authentication authResult) {
+ if (StringUtils.isNotBlank(request.getHeader(PROXY_ENTITIES_CHAIN))) {
+ response.setHeader(PROXY_ENTITIES_ACCEPTED, Boolean.TRUE.toString());
+ }
+ }
+
+ public static void unsuccessfulAuthorization(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) {
+ if (StringUtils.isNotBlank(request.getHeader(PROXY_ENTITIES_CHAIN))) {
+ response.setHeader(PROXY_ENTITIES_DETAILS, failed.getMessage());
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/nifi/blob/a40e5a07/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/anonymous/NiFiAnonymousUserFilter.java
----------------------------------------------------------------------
diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/anonymous/NiFiAnonymousUserFilter.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/anonymous/NiFiAnonymousUserFilter.java
index 295f09c..ed6e6a8 100644
--- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/anonymous/NiFiAnonymousUserFilter.java
+++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/anonymous/NiFiAnonymousUserFilter.java
@@ -16,25 +16,20 @@
*/
package org.apache.nifi.web.security.anonymous;
-import java.util.ArrayList;
-import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.nifi.admin.service.AdministrationException;
import org.apache.nifi.admin.service.UserService;
import org.apache.nifi.user.NiFiUser;
import org.apache.nifi.web.security.user.NiFiUserDetails;
-import org.apache.nifi.util.NiFiProperties;
+import org.apache.nifi.web.security.token.NiFiAuthorizationToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
-import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AnonymousAuthenticationFilter;
/**
- * Custom AnonymouseAuthenticationFilter used to grant additional authorities
- * depending on the current operating mode.
+ * Custom AnonymouseAuthenticationFilter used to grant additional authorities depending on the current operating mode.
*/
public class NiFiAnonymousUserFilter extends AnonymousAuthenticationFilter {
@@ -42,7 +37,6 @@ public class NiFiAnonymousUserFilter extends AnonymousAuthenticationFilter {
private static final String ANONYMOUS_KEY = "anonymousNifiKey";
- private NiFiProperties properties;
private UserService userService;
public NiFiAnonymousUserFilter() {
@@ -51,51 +45,28 @@ public class NiFiAnonymousUserFilter extends AnonymousAuthenticationFilter {
@Override
protected Authentication createAuthentication(HttpServletRequest request) {
- Authentication authentication;
+ Authentication authentication = null;
+
try {
// load the anonymous user from the database
NiFiUser user = userService.getUserByDn(NiFiUser.ANONYMOUS_USER_DN);
NiFiUserDetails userDetails = new NiFiUserDetails(user);
// get the granted authorities
- List<GrantedAuthority> authorities = new ArrayList<>(userDetails.getAuthorities());
- authentication = new AnonymousAuthenticationToken(ANONYMOUS_KEY, userDetails, authorities);
+ authentication = new NiFiAuthorizationToken(userDetails);
} catch (AdministrationException ase) {
// record the issue
anonymousUserFilterLogger.warn("Unable to load anonymous user from accounts database: " + ase.getMessage());
if (anonymousUserFilterLogger.isDebugEnabled()) {
anonymousUserFilterLogger.warn(StringUtils.EMPTY, ase);
}
-
- // defer to the base implementation
- authentication = super.createAuthentication(request);
}
return authentication;
}
- /**
- * Only supports anonymous users for non-secure requests or one way ssl.
- *
- * @param request request
- * @return true if allowed
- */
- @Override
- protected boolean applyAnonymousForThisRequest(HttpServletRequest request) {
- // anonymous for non secure requests
- if ("http".equalsIgnoreCase(request.getScheme())) {
- return true;
- }
-
- return !properties.getNeedClientAuth();
- }
-
/* setters */
public void setUserService(UserService userService) {
this.userService = userService;
}
- public void setProperties(NiFiProperties properties) {
- this.properties = properties;
- }
-
}
http://git-wip-us.apache.org/repos/asf/nifi/blob/a40e5a07/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/authentication/NiFiAuthenticationEntryPoint.java
----------------------------------------------------------------------
diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/authentication/NiFiAuthenticationEntryPoint.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/authentication/NiFiAuthenticationEntryPoint.java
deleted file mode 100644
index cd5f1ac..0000000
--- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/authentication/NiFiAuthenticationEntryPoint.java
+++ /dev/null
@@ -1,69 +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.nifi.web.security.authentication;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.security.core.AuthenticationException;
-import org.springframework.security.web.AuthenticationEntryPoint;
-import org.springframework.security.web.WebAttributes;
-
-/**
- * This is our own implementation of
- * org.springframework.security.web.AuthenticationEntryPoint that allows us to
- * send the response to the client exactly how we want to and log the results.
- */
-public class NiFiAuthenticationEntryPoint implements AuthenticationEntryPoint {
-
- private static final Logger logger = LoggerFactory.getLogger(NiFiAuthenticationEntryPoint.class);
-
- /**
- * Always returns a 403 error code to the client.
- *
- * @param request request
- * @param response response
- * @param ae ae
- * @throws java.io.IOException ex
- * @throws javax.servlet.ServletException ex
- */
- @Override
- public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ae) throws IOException, ServletException {
- // get the last exception - the exception that is being passed in is a generic no credentials found
- // exception because the authentication could not be found in the security context. the actual cause
- // of the problem is stored in the session as the authentication_exception
- Object authenticationException = request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
-
- // log request result
- if (authenticationException instanceof AuthenticationException) {
- ae = (AuthenticationException) authenticationException;
- logger.info(String.format("Rejecting access to web api: %s", ae.getMessage()));
- }
-
- // set the response status
- response.setStatus(HttpServletResponse.SC_FORBIDDEN);
- response.setContentType("text/plain");
-
- // write the response message
- PrintWriter out = response.getWriter();
- out.println("Access is denied.");
- }
-}
http://git-wip-us.apache.org/repos/asf/nifi/blob/a40e5a07/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/authorization/NiFiAuthorizationService.java
----------------------------------------------------------------------
diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/authorization/NiFiAuthorizationService.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/authorization/NiFiAuthorizationService.java
index 95b4669..c3a5e43 100644
--- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/authorization/NiFiAuthorizationService.java
+++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/authorization/NiFiAuthorizationService.java
@@ -16,34 +16,35 @@
*/
package org.apache.nifi.web.security.authorization;
-import java.util.Deque;
-import java.util.Iterator;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.ListIterator;
+import org.apache.commons.lang3.StringUtils;
import org.apache.nifi.admin.service.AccountDisabledException;
import org.apache.nifi.admin.service.AccountNotFoundException;
import org.apache.nifi.admin.service.AccountPendingException;
import org.apache.nifi.admin.service.AdministrationException;
import org.apache.nifi.admin.service.UserService;
import org.apache.nifi.authorization.Authority;
-import org.apache.nifi.web.security.DnUtils;
import org.apache.nifi.user.NiFiUser;
-import org.apache.commons.lang3.StringUtils;
+import org.apache.nifi.util.NiFiProperties;
import org.apache.nifi.web.security.UntrustedProxyException;
import org.apache.nifi.web.security.user.NiFiUserDetails;
-import org.apache.nifi.util.NiFiProperties;
+import org.apache.nifi.web.security.token.NiFiAuthenticationRequestToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.AccountStatusException;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
-import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
/**
* UserDetailsService that will verify user identity and grant user authorities.
*/
-public class NiFiAuthorizationService implements UserDetailsService {
+public class NiFiAuthorizationService implements AuthenticationUserDetailsService<NiFiAuthenticationRequestToken> {
private static final Logger logger = LoggerFactory.getLogger(NiFiAuthorizationService.class);
@@ -58,30 +59,30 @@ public class NiFiAuthorizationService implements UserDetailsService {
* made for each individual request as a whole (without other request
* potentially impacting it).
*
- * @param rawProxyChain proxy chain
+ * @param request request
* @return user details
* @throws UsernameNotFoundException ex
* @throws org.springframework.dao.DataAccessException ex
*/
@Override
- public synchronized UserDetails loadUserByUsername(String rawProxyChain) throws UsernameNotFoundException, DataAccessException {
+ public synchronized UserDetails loadUserDetails(NiFiAuthenticationRequestToken request) throws UsernameNotFoundException, DataAccessException {
NiFiUserDetails userDetails = null;
- final Deque<String> dnList = DnUtils.tokenizeProxyChain(rawProxyChain);
+ final List<String> chain = new ArrayList<>(request.getChain());
// ensure valid input
- if (dnList.size() == 0) {
- logger.warn("Malformed proxy chain: " + rawProxyChain);
+ if (chain.isEmpty()) {
+ logger.warn("Malformed proxy chain: " + StringUtils.join(request.getChain()));
throw new UntrustedProxyException("Malformed proxy chain.");
}
NiFiUser proxy = null;
// process each part of the proxy chain
- for (final Iterator<String> dnIter = dnList.iterator(); dnIter.hasNext();) {
- final String dn = dnIter.next();
+ for (final ListIterator<String> chainIter = request.getChain().listIterator(chain.size()); chainIter.hasPrevious();) {
+ final String dn = chainIter.previous();
// if there is another dn after this one, this dn is a proxy for the request
- if (dnIter.hasNext()) {
+ if (chainIter.hasPrevious()) {
try {
// get the user details for the proxy
final NiFiUserDetails proxyDetails = getNiFiUserDetails(dn);
@@ -110,7 +111,7 @@ public class NiFiAuthorizationService implements UserDetailsService {
userService.createPendingUserAccount(dn, "Automatic account request generated for unknown proxy.");
// propagate the exception to return the appropriate response
- throw new UsernameNotFoundException(String.format("An account request was generated for the proxy '%s'.", dn));
+ throw new UntrustedProxyException(String.format("An account request was generated for the proxy '%s'.", dn));
} catch (AdministrationException ae) {
throw new AuthenticationServiceException(String.format("Unable to create an account request for '%s': %s", dn, ae.getMessage()), ae);
} catch (IllegalArgumentException iae) {
http://git-wip-us.apache.org/repos/asf/nifi/blob/a40e5a07/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/authorization/NodeAuthorizedUserFilter.java
----------------------------------------------------------------------
diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/authorization/NodeAuthorizedUserFilter.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/authorization/NodeAuthorizedUserFilter.java
deleted file mode 100644
index 80feed7..0000000
--- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/authorization/NodeAuthorizedUserFilter.java
+++ /dev/null
@@ -1,128 +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.nifi.web.security.authorization;
-
-import java.io.IOException;
-import java.io.Serializable;
-import java.security.cert.X509Certificate;
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import org.apache.nifi.controller.FlowController;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.nifi.web.security.user.NiFiUserDetails;
-import org.apache.nifi.web.security.x509.SubjectDnX509PrincipalExtractor;
-import org.apache.nifi.web.security.x509.X509CertificateExtractor;
-import org.apache.nifi.user.NiFiUser;
-import org.apache.nifi.util.NiFiProperties;
-import org.apache.nifi.web.util.WebUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.context.ApplicationContext;
-import org.springframework.security.authentication.AuthenticationDetailsSource;
-import org.springframework.security.core.context.SecurityContextHolder;
-import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
-import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
-import org.springframework.security.web.authentication.preauth.x509.X509PrincipalExtractor;
-import org.springframework.web.context.support.WebApplicationContextUtils;
-import org.springframework.web.filter.GenericFilterBean;
-
-/**
- * Custom filter to extract a user's authorities from the request where the user
- * was authenticated by the cluster manager and populate the threadlocal with
- * the authorized user. If the request contains the appropriate header with
- * authorities and the application instance is a node connected to the cluster,
- * then the authentication/authorization steps remaining in the filter chain are
- * skipped.
- *
- * Checking if the application instance is a connected node is important because
- * it prevents external clients from faking the request headers and bypassing
- * the authentication processing chain.
- */
-public class NodeAuthorizedUserFilter extends GenericFilterBean {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(NodeAuthorizedUserFilter.class);
-
- public static final String PROXY_USER_DETAILS = "X-ProxiedEntityUserDetails";
-
- private NiFiProperties properties;
- private final AuthenticationDetailsSource authenticationDetailsSource = new WebAuthenticationDetailsSource();
- private final X509CertificateExtractor certificateExtractor = new X509CertificateExtractor();
- private final X509PrincipalExtractor principalExtractor = new SubjectDnX509PrincipalExtractor();
-
- @Override
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
- final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
-
- // get the proxied user's authorities
- final String hexEncodedUserDetails = httpServletRequest.getHeader(PROXY_USER_DETAILS);
-
- // check if the request has the necessary header information and this instance is configured as a node
- if (StringUtils.isNotBlank(hexEncodedUserDetails) && properties.isNode()) {
-
- // get the flow controller from the Spring context
- final ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
- final FlowController flowController = ctx.getBean("flowController", FlowController.class);
-
- // check that we are connected to the cluster
- if (flowController.getNodeId() != null) {
- try {
- // get the DN from the cert in the request
- final X509Certificate certificate = certificateExtractor.extractClientCertificate((HttpServletRequest) request);
- if (certificate != null) {
- // extract the principal from the certificate
- final Object certificatePrincipal = principalExtractor.extractPrincipal(certificate);
- final String dn = certificatePrincipal.toString();
-
- // only consider the pre-authorized user when the request came from the NCM according to the DN in the certificate
- final String clusterManagerDN = flowController.getClusterManagerDN();
- if (clusterManagerDN != null && clusterManagerDN.equals(dn)) {
- // deserialize hex encoded object
- final Serializable userDetailsObj = WebUtils.deserializeHexToObject(hexEncodedUserDetails);
-
- // if we have a valid object, set the authentication token and bypass the remaining authentication processing chain
- if (userDetailsObj instanceof NiFiUserDetails) {
- final NiFiUserDetails userDetails = (NiFiUserDetails) userDetailsObj;
- final NiFiUser user = userDetails.getNiFiUser();
-
- // log the request attempt - response details will be logged later
- logger.info(String.format("Attempting request for (%s) %s %s (source ip: %s)", user.getDn(), httpServletRequest.getMethod(),
- httpServletRequest.getRequestURL().toString(), request.getRemoteAddr()));
-
- // we do not create the authentication token with the X509 certificate because the certificate is from the sending system, not the proxied user
- final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(userDetails, null, userDetails.getAuthorities());
- token.setDetails(authenticationDetailsSource.buildDetails(request));
- SecurityContextHolder.getContext().setAuthentication(token);
- }
- }
- }
- } catch (final ClassNotFoundException cnfe) {
- LOGGER.warn("Classpath issue detected because failed to deserialize authorized user in request header due to: " + cnfe, cnfe);
- }
- }
- }
-
- chain.doFilter(request, response);
- }
-
- /* setters */
- public void setProperties(NiFiProperties properties) {
- this.properties = properties;
- }
-}
http://git-wip-us.apache.org/repos/asf/nifi/blob/a40e5a07/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/form/LoginAuthenticationFilter.java
----------------------------------------------------------------------
diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/form/LoginAuthenticationFilter.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/form/LoginAuthenticationFilter.java
new file mode 100644
index 0000000..565b56b
--- /dev/null
+++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/form/LoginAuthenticationFilter.java
@@ -0,0 +1,131 @@
+/*
+ * 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.nifi.web.security.form;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.security.cert.X509Certificate;
+import java.util.List;
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.apache.nifi.authentication.LoginCredentials;
+import org.apache.nifi.authentication.LoginIdentityProvider;
+import org.apache.nifi.web.security.ProxiedEntitiesUtils;
+import org.apache.nifi.web.security.jwt.JwtService;
+import org.apache.nifi.web.security.token.NiFiAuthenticationRequestToken;
+import org.apache.nifi.web.security.token.LoginAuthenticationRequestToken;
+import org.apache.nifi.web.security.x509.X509CertificateExtractor;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
+import org.springframework.security.web.authentication.preauth.x509.X509PrincipalExtractor;
+
+/**
+ * Exchanges a successful login with the configured provider for a ID token for accessing the API.
+ */
+public class LoginAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
+
+ private static final Logger logger = LoggerFactory.getLogger(LoginAuthenticationFilter.class);
+
+ private X509CertificateExtractor certificateExtractor;
+ private X509PrincipalExtractor principalExtractor;
+
+ private JwtService jwtService;
+ private LoginIdentityProvider loginIdentityProvider;
+
+ public LoginAuthenticationFilter(final String defaultFilterProcessesUrl) {
+ super(defaultFilterProcessesUrl);
+
+ // do not continue filter chain... simply exchaning authentication for token
+ setContinueChainBeforeSuccessfulAuthentication(false);
+ }
+
+ @Override
+ public Authentication attemptAuthentication(final HttpServletRequest request, final HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
+ // only suppport login when running securely
+ if (!request.isSecure()) {
+ return null;
+ }
+
+ // look for a certificate
+ final X509Certificate certificate = certificateExtractor.extractClientCertificate(request);
+
+ // ensure the cert was found
+ if (certificate != null) {
+ // extract the principal
+ Object certificatePrincipal = principalExtractor.extractPrincipal(certificate);
+ final String principal = ProxiedEntitiesUtils.formatProxyDn(certificatePrincipal.toString());
+
+ final List<String> proxyChain = ProxiedEntitiesUtils.buildProxyChain(request, principal);
+ return new NiFiAuthenticationRequestToken(proxyChain);
+ } else {
+ // if there were no certificate or no principal, defer to the login provider
+ final LoginCredentials credentials = getLoginCredentials(request);
+
+ // if unable to authenticate return null
+ if (credentials == null) {
+ return null;
+ }
+
+ final List<String> proxyChain = ProxiedEntitiesUtils.buildProxyChain(request, credentials.getUsername());
+ return new LoginAuthenticationRequestToken(proxyChain, credentials);
+ }
+ }
+
+ private LoginCredentials getLoginCredentials(HttpServletRequest request) {
+ return new LoginCredentials(request.getParameter("username"), request.getParameter("password"));
+ }
+
+ @Override
+ protected void successfulAuthentication(final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain, final Authentication authentication)
+ throws IOException, ServletException {
+
+ // generate JWT for response
+ jwtService.addToken(response, authentication);
+ }
+
+ @Override
+ protected void unsuccessfulAuthentication(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException failed) throws IOException, ServletException {
+ // set the response status
+ response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ response.setContentType("text/plain");
+
+ final PrintWriter out = response.getWriter();
+ out.println("Invalid username/password");
+ }
+
+ public void setJwtService(JwtService jwtService) {
+ this.jwtService = jwtService;
+ }
+
+ public void setLoginIdentityProvider(LoginIdentityProvider loginIdentityProvider) {
+ this.loginIdentityProvider = loginIdentityProvider;
+ }
+
+ public void setCertificateExtractor(X509CertificateExtractor certificateExtractor) {
+ this.certificateExtractor = certificateExtractor;
+ }
+
+ public void setPrincipalExtractor(X509PrincipalExtractor principalExtractor) {
+ this.principalExtractor = principalExtractor;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/nifi/blob/a40e5a07/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/form/LoginAuthenticationProvider.java
----------------------------------------------------------------------
diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/form/LoginAuthenticationProvider.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/form/LoginAuthenticationProvider.java
new file mode 100644
index 0000000..16e5288
--- /dev/null
+++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/form/LoginAuthenticationProvider.java
@@ -0,0 +1,53 @@
+/*
+ * 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.nifi.web.security.form;
+
+import org.apache.nifi.authentication.LoginIdentityProvider;
+import org.apache.nifi.web.security.token.LoginAuthenticationRequestToken;
+import org.apache.nifi.web.security.token.LoginAuthenticationToken;
+import org.springframework.security.authentication.AuthenticationProvider;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+
+/**
+ *
+ */
+public class LoginAuthenticationProvider implements AuthenticationProvider {
+
+ private LoginIdentityProvider loginIdentityProvider;
+
+ @Override
+ public Authentication authenticate(Authentication authentication) throws AuthenticationException {
+ final LoginAuthenticationRequestToken loginAuthenticationToken = (LoginAuthenticationRequestToken) authentication;
+
+ if (loginIdentityProvider.authenticate(loginAuthenticationToken.getLoginCredentials())) {
+ return new LoginAuthenticationToken(loginAuthenticationToken.getLoginCredentials());
+ } else {
+ return null;
+ }
+ }
+
+ @Override
+ public boolean supports(Class<?> authentication) {
+ return LoginAuthenticationRequestToken.class.isAssignableFrom(authentication);
+ }
+
+ public void setLoginIdentityProvider(LoginIdentityProvider loginIdentityProvider) {
+ this.loginIdentityProvider = loginIdentityProvider;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/nifi/blob/a40e5a07/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/jwt/JwtAuthenticationFilter.java
----------------------------------------------------------------------
diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/jwt/JwtAuthenticationFilter.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/jwt/JwtAuthenticationFilter.java
new file mode 100644
index 0000000..a628ff6
--- /dev/null
+++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/jwt/JwtAuthenticationFilter.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.nifi.web.security.jwt;
+
+import java.util.List;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.apache.nifi.web.security.NiFiAuthenticationFilter;
+import org.apache.nifi.web.security.ProxiedEntitiesUtils;
+import org.apache.nifi.web.security.token.NewAccountAuthenticationRequestToken;
+import org.apache.nifi.web.security.token.NiFiAuthenticationRequestToken;
+import org.apache.nifi.web.security.user.NewAccountRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.security.core.Authentication;
+
+/**
+ */
+public class JwtAuthenticationFilter extends NiFiAuthenticationFilter {
+
+ private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);
+
+ private JwtService jwtService;
+
+ @Override
+ public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {
+ // only suppport jwt login when running securely
+ if (!request.isSecure()) {
+ return null;
+ }
+
+ final String principal = jwtService.getAuthentication(request);
+ if (principal == null) {
+ return null;
+ }
+
+ final List<String> proxyChain = ProxiedEntitiesUtils.buildProxyChain(request, principal);
+ if (isNewAccountRequest(request)) {
+ return new NewAccountAuthenticationRequestToken(new NewAccountRequest(proxyChain, getJustification(request)));
+ } else {
+ return new NiFiAuthenticationRequestToken(proxyChain);
+ }
+ }
+
+ public void setJwtService(JwtService jwtService) {
+ this.jwtService = jwtService;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/nifi/blob/a40e5a07/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/jwt/JwtAuthenticationProvider.java
----------------------------------------------------------------------
diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/jwt/JwtAuthenticationProvider.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/jwt/JwtAuthenticationProvider.java
new file mode 100644
index 0000000..ae459b0
--- /dev/null
+++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/jwt/JwtAuthenticationProvider.java
@@ -0,0 +1,47 @@
+/*
+ * 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.nifi.web.security.jwt;
+
+import org.apache.nifi.web.security.token.NewAccountAuthenticationRequestToken;
+import org.apache.nifi.web.security.token.NewAccountAuthenticationToken;
+import org.apache.nifi.web.security.token.NiFiAuthenticationRequestToken;
+import org.springframework.security.authentication.AuthenticationProvider;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+
+/**
+ *
+ */
+public class JwtAuthenticationProvider implements AuthenticationProvider {
+
+ @Override
+ public Authentication authenticate(Authentication authentication) throws AuthenticationException {
+ if (NewAccountAuthenticationRequestToken.class.isAssignableFrom(authentication.getClass())) {
+ return new NewAccountAuthenticationToken(((NewAccountAuthenticationRequestToken) authentication).getNewAccountRequest());
+ } else if (NiFiAuthenticationRequestToken.class.isAssignableFrom(authentication.getClass())) {
+ return authentication;
+ } else {
+ return null;
+ }
+ }
+
+ @Override
+ public boolean supports(Class<?> authentication) {
+ return NiFiAuthenticationRequestToken.class.isAssignableFrom(authentication);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/nifi/blob/a40e5a07/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/jwt/JwtService.java
----------------------------------------------------------------------
diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/jwt/JwtService.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/jwt/JwtService.java
new file mode 100644
index 0000000..cfe7073
--- /dev/null
+++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/jwt/JwtService.java
@@ -0,0 +1,51 @@
+/*
+ * 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.nifi.web.security.jwt;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.springframework.security.core.Authentication;
+
+/**
+ *
+ */
+public class JwtService {
+
+ /**
+ * Gets the Authentication by extracting a JWT token from the specified request.
+ *
+ * @param request Request to extract the token from
+ * @return The user identifier from the token
+ */
+ public String getAuthentication(final HttpServletRequest request) {
+ // extract/verify token from incoming request
+ // load user details with identifier from token
+ // create authentication using user details
+ return null;
+ }
+
+ /**
+ * Adds a token for the specified authentication in the specified response.
+ *
+ * @param response The response to add the token to
+ * @param authentication The authentication to generate a token for
+ */
+ public void addToken(final HttpServletResponse response, final Authentication authentication) {
+ // create a token the specified authentication
+ // add the token as a response header
+ }
+}
http://git-wip-us.apache.org/repos/asf/nifi/blob/a40e5a07/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/node/NodeAuthorizedUserFilter.java
----------------------------------------------------------------------
diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/node/NodeAuthorizedUserFilter.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/node/NodeAuthorizedUserFilter.java
new file mode 100644
index 0000000..e73fd9e
--- /dev/null
+++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/node/NodeAuthorizedUserFilter.java
@@ -0,0 +1,127 @@
+/*
+ * 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.nifi.web.security.node;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.security.cert.X509Certificate;
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import org.apache.nifi.controller.FlowController;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.nifi.web.security.user.NiFiUserDetails;
+import org.apache.nifi.web.security.x509.SubjectDnX509PrincipalExtractor;
+import org.apache.nifi.web.security.x509.X509CertificateExtractor;
+import org.apache.nifi.user.NiFiUser;
+import org.apache.nifi.util.NiFiProperties;
+import org.apache.nifi.web.util.WebUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.context.ApplicationContext;
+import org.springframework.security.authentication.AuthenticationDetailsSource;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
+import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
+import org.springframework.security.web.authentication.preauth.x509.X509PrincipalExtractor;
+import org.springframework.web.context.support.WebApplicationContextUtils;
+import org.springframework.web.filter.GenericFilterBean;
+
+/**
+ * Custom filter to extract a user's authorities from the request where the user
+ * was authenticated by the cluster manager and populate the threadlocal with
+ * the authorized user. If the request contains the appropriate header with
+ * authorities and the application instance is a node connected to the cluster,
+ * then the authentication/authorization steps remaining in the filter chain are
+ * skipped.
+ *
+ * Checking if the application instance is a connected node is important because
+ * it prevents external clients from faking the request headers and bypassing
+ * the authentication processing chain.
+ */
+public class NodeAuthorizedUserFilter extends GenericFilterBean {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(NodeAuthorizedUserFilter.class);
+
+ public static final String PROXY_USER_DETAILS = "X-ProxiedEntityUserDetails";
+
+ private final NiFiProperties properties;
+ private final AuthenticationDetailsSource authenticationDetailsSource = new WebAuthenticationDetailsSource();
+ private final X509CertificateExtractor certificateExtractor = new X509CertificateExtractor();
+ private final X509PrincipalExtractor principalExtractor = new SubjectDnX509PrincipalExtractor();
+
+ public NodeAuthorizedUserFilter(NiFiProperties properties) {
+ this.properties = properties;
+ }
+
+ @Override
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
+ final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
+
+ // get the proxied user's authorities
+ final String hexEncodedUserDetails = httpServletRequest.getHeader(PROXY_USER_DETAILS);
+
+ // check if the request has the necessary header information and this instance is configured as a node
+ if (StringUtils.isNotBlank(hexEncodedUserDetails) && properties.isNode()) {
+
+ // get the flow controller from the Spring context
+ final ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
+ final FlowController flowController = ctx.getBean("flowController", FlowController.class);
+
+ // check that we are connected to the cluster
+ if (flowController.getNodeId() != null) {
+ try {
+ // get the DN from the cert in the request
+ final X509Certificate certificate = certificateExtractor.extractClientCertificate((HttpServletRequest) request);
+ if (certificate != null) {
+ // extract the principal from the certificate
+ final Object certificatePrincipal = principalExtractor.extractPrincipal(certificate);
+ final String dn = certificatePrincipal.toString();
+
+ // only consider the pre-authorized user when the request came from the NCM according to the DN in the certificate
+ final String clusterManagerDN = flowController.getClusterManagerDN();
+ if (clusterManagerDN != null && clusterManagerDN.equals(dn)) {
+ // deserialize hex encoded object
+ final Serializable userDetailsObj = WebUtils.deserializeHexToObject(hexEncodedUserDetails);
+
+ // if we have a valid object, set the authentication token and bypass the remaining authentication processing chain
+ if (userDetailsObj instanceof NiFiUserDetails) {
+ final NiFiUserDetails userDetails = (NiFiUserDetails) userDetailsObj;
+ final NiFiUser user = userDetails.getNiFiUser();
+
+ // log the request attempt - response details will be logged later
+ logger.info(String.format("Attempting request for (%s) %s %s (source ip: %s)", user.getDn(), httpServletRequest.getMethod(),
+ httpServletRequest.getRequestURL().toString(), request.getRemoteAddr()));
+
+ // we do not create the authentication token with the X509 certificate because the certificate is from the sending system, not the proxied user
+ final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(userDetails, null, userDetails.getAuthorities());
+ token.setDetails(authenticationDetailsSource.buildDetails(request));
+ SecurityContextHolder.getContext().setAuthentication(token);
+ }
+ }
+ }
+ } catch (final ClassNotFoundException cnfe) {
+ LOGGER.warn("Classpath issue detected because failed to deserialize authorized user in request header due to: " + cnfe, cnfe);
+ }
+ }
+ }
+
+ chain.doFilter(request, response);
+ }
+}