You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@nifi.apache.org by bb...@apache.org on 2017/11/21 16:17:35 UTC
[2/4] nifi-registry git commit: NIFIREG-45 Refactor
LoginIdentityProvider interface as a more generic and flexible
IdentityProvider interface
http://git-wip-us.apache.org/repos/asf/nifi-registry/blob/ef8ba127/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/IdentityAuthenticationFilter.java
----------------------------------------------------------------------
diff --git a/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/IdentityAuthenticationFilter.java b/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/IdentityAuthenticationFilter.java
new file mode 100644
index 0000000..7c2b27f
--- /dev/null
+++ b/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/IdentityAuthenticationFilter.java
@@ -0,0 +1,203 @@
+/*
+ * 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.registry.web.security.authentication;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.nifi.registry.security.authentication.AuthenticationRequest;
+import org.apache.nifi.registry.security.authentication.IdentityProvider;
+import org.apache.nifi.registry.security.authorization.user.NiFiUserUtils;
+import org.apache.nifi.registry.security.util.ProxiedEntitiesUtils;
+import org.apache.nifi.registry.web.security.authentication.exception.InvalidAuthenticationException;
+import org.apache.nifi.registry.web.security.authentication.exception.UntrustedProxyException;
+import org.springframework.security.authentication.AuthenticationManager;
+import org.springframework.security.authentication.AuthenticationServiceException;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
+import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
+import org.springframework.security.web.util.matcher.RequestMatcher;
+
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.Collection;
+
+/**
+ * Note: This class is deprecated and is being considered for complete removal in favor of using {@link IdentityFilter}.
+ * It is remaining in place for the time being until the pattern of authentication implemented by {@link IdentityFilter}
+ * has been more thoroughly vetted in real use.
+ */
+@Deprecated
+public class IdentityAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
+
+ private static final RequestMatcher requiresAuthenticationRequestMatcher = new RequestMatcher() {
+ @Override
+ public boolean matches(HttpServletRequest httpServletRequest) {
+ return NiFiUserUtils.getNiFiUser() == null;
+ }
+ };
+
+ private final IdentityProvider identityProvider;
+
+ public IdentityAuthenticationFilter(IdentityProvider identityProvider, AuthenticationManager authenticationManager, String defaultFilterProcessesUrl) {
+ super(defaultFilterProcessesUrl);
+ super.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher(defaultFilterProcessesUrl)); // Authentication will only be initiated for the request url matching this pattern
+ setAuthenticationManager(authenticationManager);
+ this.identityProvider = identityProvider;
+ }
+
+ public IdentityAuthenticationFilter(IdentityProvider identityProvider, AuthenticationManager authenticationManager) {
+ super(requiresAuthenticationRequestMatcher);
+ setAuthenticationManager(authenticationManager);
+ this.identityProvider = identityProvider;
+ }
+
+ @Override
+ public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {
+
+ // Only require authentication from an identity provider if the NiFi registry is running securely.
+ if (!httpServletRequest.isSecure()) {
+ // Otherwise, requests will be "authenticated" by the AnonymousIdentityFilter
+ //return null;
+ return new ContinueFilterChainAuthentication(); // see successfulAuthentication for why we do this
+ }
+
+ AuthenticationRequest authenticationRequest = identityProvider.extractCredentials(httpServletRequest);
+ if (authenticationRequest == null) {
+ //return null;
+ return new ContinueFilterChainAuthentication(); // see successfulAuthentication for why we do this
+ }
+ Authentication authentication = new AuthenticationRequestToken(authenticationRequest, identityProvider.getClass(), httpServletRequest.getRemoteAddr());
+ Authentication authenticationResult = getAuthenticationManager().authenticate(authentication); // See IdentityProviderAuthenticationProvider for authentication impl.
+ if (authenticationResult == null) {
+ return new ContinueFilterChainAuthentication(); // see successfulAuthentication for why we do this
+ } else {
+ return authenticationResult;
+ }
+ // Super class will invoke successfulAuthentication() or unsuccessfulAuthentication() depending on the outcome of the authentication attempt
+ }
+
+ @Override
+ protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
+
+ if (authResult.getClass().equals(ContinueFilterChainAuthentication.class)) {
+ logger.info("Authentication unknown, continue chain");
+ // Because this NiFi Registry might be configured with multiple AbstractAuthenticationProcessingFilter's,
+ // the request should continue through the filter chain. If none of the IdentityProviderAuthenticationFilters
+ // can authenticate the request and register a user identity, then the AnonymousIdentityFilter will assign the
+ // Anonymous identity which will not be authorized for access.
+ // A refinement of this would be to extend something other than AbstractAuthenticationProcessingFilter, such as
+ // GenericFilterBean, or to register different filter chains based on context, such as only include
+ // AbstractAuthenticationProcessingFilter(s) when running securely, otherwise don't register any and only register
+ // the AnonymousIdentityFilter.
+ chain.doFilter(request, response);
+ }
+
+ logger.info("Authentication success for " + authResult);
+
+ SecurityContextHolder.getContext().setAuthentication(authResult);
+ if (StringUtils.isNotBlank(request.getHeader(ProxiedEntitiesUtils.PROXY_ENTITIES_CHAIN))) {
+ response.setHeader(ProxiedEntitiesUtils.PROXY_ENTITIES_ACCEPTED, Boolean.TRUE.toString());
+ }
+
+ // continue the filter chain, which now holds a NiFiUser in the SecurityContext's authentication
+ chain.doFilter(request, response);
+ }
+
+ @Override
+ protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
+ this.logger.debug("Authentication request failed: " + failed.toString(), failed);
+
+ SecurityContextHolder.clearContext();
+ this.logger.debug("Updated SecurityContextHolder to contain null Authentication");
+
+ // populate the response
+ if (StringUtils.isNotBlank(request.getHeader(ProxiedEntitiesUtils.PROXY_ENTITIES_CHAIN))) {
+ response.setHeader(ProxiedEntitiesUtils.PROXY_ENTITIES_DETAILS, failed.getMessage());
+ }
+
+ // set the response status
+ response.setContentType("text/plain");
+
+ // write the response message
+ PrintWriter out = response.getWriter();
+
+ // use the type of authentication exception to determine the response code
+ if (failed instanceof InvalidAuthenticationException) {
+ response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ out.println(failed.getMessage());
+ } else if (failed instanceof UntrustedProxyException) { // thrown in X509IdentityProviderAuthenticationProvider
+ response.setStatus(HttpServletResponse.SC_FORBIDDEN);
+ out.println(failed.getMessage());
+ } else if (failed instanceof AuthenticationServiceException) {
+ logger.error(String.format("Unable to authorize: %s", failed.getMessage()), failed);
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ out.println(String.format("Unable to authorize: %s", failed.getMessage()));
+ } else {
+ logger.error(String.format("Unable to authorize: %s", failed.getMessage()), failed);
+ response.setStatus(HttpServletResponse.SC_FORBIDDEN);
+ out.println("Access is denied.");
+ }
+
+ // log the failure
+ logger.warn(String.format("Rejecting access to web api: %s", failed.getMessage()));
+ logger.debug(StringUtils.EMPTY, failed);
+ }
+
+ protected class ContinueFilterChainAuthentication implements Authentication {
+ @Override
+ public Collection<? extends GrantedAuthority> getAuthorities() {
+ return null;
+ }
+
+ @Override
+ public Object getCredentials() {
+ return null;
+ }
+
+ @Override
+ public Object getDetails() {
+ return null;
+ }
+
+ @Override
+ public Object getPrincipal() {
+ return null;
+ }
+
+ @Override
+ public boolean isAuthenticated() {
+ return false;
+ }
+
+ @Override
+ public void setAuthenticated(boolean b) throws IllegalArgumentException {
+ throw new IllegalArgumentException("Cannot set authenticated on ContinueFilterChainAuthentication");
+ }
+
+ @Override
+ public String getName() {
+ return null;
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/nifi-registry/blob/ef8ba127/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/IdentityAuthenticationProvider.java
----------------------------------------------------------------------
diff --git a/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/IdentityAuthenticationProvider.java b/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/IdentityAuthenticationProvider.java
new file mode 100644
index 0000000..67c45d8
--- /dev/null
+++ b/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/IdentityAuthenticationProvider.java
@@ -0,0 +1,140 @@
+/*
+ * 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.registry.web.security.authentication;
+
+import org.apache.nifi.registry.properties.NiFiRegistryProperties;
+import org.apache.nifi.registry.properties.util.IdentityMapping;
+import org.apache.nifi.registry.properties.util.IdentityMappingUtil;
+import org.apache.nifi.registry.security.authentication.AuthenticationRequest;
+import org.apache.nifi.registry.security.authentication.AuthenticationResponse;
+import org.apache.nifi.registry.security.authentication.IdentityProvider;
+import org.apache.nifi.registry.security.authentication.exception.InvalidCredentialsException;
+import org.apache.nifi.registry.security.authorization.Authorizer;
+import org.apache.nifi.registry.security.authorization.Group;
+import org.apache.nifi.registry.security.authorization.ManagedAuthorizer;
+import org.apache.nifi.registry.security.authorization.UserAndGroups;
+import org.apache.nifi.registry.security.authorization.UserGroupProvider;
+import org.apache.nifi.registry.security.authorization.user.NiFiUserDetails;
+import org.apache.nifi.registry.security.authorization.user.StandardNiFiUser;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.security.authentication.AuthenticationProvider;
+import org.springframework.security.authentication.BadCredentialsException;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+public class IdentityAuthenticationProvider implements AuthenticationProvider {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(IdentityAuthenticationProvider.class);
+
+ protected NiFiRegistryProperties properties;
+ protected Authorizer authorizer;
+ protected final IdentityProvider identityProvider;
+ private List<IdentityMapping> mappings;
+
+ public IdentityAuthenticationProvider(
+ NiFiRegistryProperties properties,
+ Authorizer authorizer,
+ IdentityProvider identityProvider) {
+ this.properties = properties;
+ this.authorizer = authorizer;
+ this.identityProvider = identityProvider;
+ this.mappings = Collections.unmodifiableList(IdentityMappingUtil.getIdentityMappings(properties));
+ }
+
+ @Override
+ public Authentication authenticate(Authentication authentication) throws AuthenticationException {
+
+ // Determine if this AuthenticationProvider's identityProvider should be able to support this AuthenticationRequest
+ boolean tokenOriginatedFromThisIdentityProvider = checkTokenOriginatedFromThisIdentityProvider(authentication);
+
+ if (!tokenOriginatedFromThisIdentityProvider) {
+ // Returning null indicates to The Spring Security AuthenticationManager that this AuthenticationProvider
+ // cannot authenticate this token and another provider should be tried.
+ return null;
+ }
+
+ AuthenticationRequestToken authenticationRequestToken = ((AuthenticationRequestToken)authentication);
+ AuthenticationRequest authenticationRequest = authenticationRequestToken.getAuthenticationRequest();
+
+ try {
+ AuthenticationResponse authenticationResponse = identityProvider.authenticate(authenticationRequest);
+ if (authenticationResponse == null) {
+ return null;
+ }
+ return buildAuthenticatedToken(authenticationRequestToken, authenticationResponse);
+ } catch (InvalidCredentialsException e) {
+ throw new BadCredentialsException("Identity Provider authentication failed.", e);
+ }
+
+ }
+
+ @Override
+ public boolean supports(Class<?> authenticationClazz) {
+ // is authenticationClazz a subclass of AuthenticationRequestWrapper?
+ return AuthenticationRequestToken.class.isAssignableFrom(authenticationClazz);
+ }
+
+ protected AuthenticationSuccessToken buildAuthenticatedToken(
+ AuthenticationRequestToken requestToken,
+ AuthenticationResponse response) {
+
+ final String mappedIdentity = mapIdentity(response.getIdentity());
+
+ return new AuthenticationSuccessToken(new NiFiUserDetails(
+ new StandardNiFiUser.Builder()
+ .identity(mappedIdentity)
+ .groups(getUserGroups(mappedIdentity))
+ .clientAddress(requestToken.getClientAddress())
+ .build()));
+ }
+
+ protected boolean checkTokenOriginatedFromThisIdentityProvider(Authentication authentication) {
+ return (authentication instanceof AuthenticationRequestToken
+ && identityProvider.getClass().equals(((AuthenticationRequestToken) authentication).getAuthenticationRequestOrigin()));
+ }
+
+ protected String mapIdentity(final String identity) {
+ return IdentityMappingUtil.mapIdentity(identity, mappings);
+ }
+
+ protected Set<String> getUserGroups(final String identity) {
+ return getUserGroups(authorizer, identity);
+ }
+
+ private static Set<String> getUserGroups(final Authorizer authorizer, final String userIdentity) {
+ if (authorizer instanceof ManagedAuthorizer) {
+ final ManagedAuthorizer managedAuthorizer = (ManagedAuthorizer) authorizer;
+ final UserGroupProvider userGroupProvider = managedAuthorizer.getAccessPolicyProvider().getUserGroupProvider();
+ final UserAndGroups userAndGroups = userGroupProvider.getUserAndGroups(userIdentity);
+ final Set<Group> userGroups = userAndGroups.getGroups();
+
+ if (userGroups == null || userGroups.isEmpty()) {
+ return Collections.EMPTY_SET;
+ } else {
+ return userAndGroups.getGroups().stream().map(Group::getName).collect(Collectors.toSet());
+ }
+ } else {
+ return null;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/nifi-registry/blob/ef8ba127/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/IdentityFilter.java
----------------------------------------------------------------------
diff --git a/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/IdentityFilter.java b/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/IdentityFilter.java
new file mode 100644
index 0000000..40c2662
--- /dev/null
+++ b/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/IdentityFilter.java
@@ -0,0 +1,97 @@
+/*
+ * 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.registry.web.security.authentication;
+
+import org.apache.nifi.registry.security.authentication.AuthenticationRequest;
+import org.apache.nifi.registry.security.authentication.IdentityProvider;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.web.filter.GenericFilterBean;
+
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import java.io.IOException;
+
+/**
+ * A class that will extract an identity / credentials claim from an HttpServlet Request using an injected IdentityProvider.
+ *
+ * This class is designed to be used in collaboration with an {@link IdentityAuthenticationProvider}. The identity/credentials will be
+ * extracted by this filter and later validated by the {@link IdentityAuthenticationProvider} in the default SecurityInterceptorFilter.
+ */
+public class IdentityFilter extends GenericFilterBean {
+
+ private static final Logger logger = LoggerFactory.getLogger(IdentityFilter.class);
+
+ private final IdentityProvider identityProvider;
+
+ public IdentityFilter(IdentityProvider identityProvider) {
+ this.identityProvider = identityProvider;
+ }
+
+ @Override
+ public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
+
+ // Only require authentication from an identity provider if the NiFi registry is running securely.
+ if (!servletRequest.isSecure()) {
+ // Otherwise, requests will be "authenticated" by the AnonymousIdentityFilter
+ filterChain.doFilter(servletRequest, servletResponse);
+ return;
+ }
+
+ if (identityProvider == null) {
+ logger.warn("Identity Filter configured with NULL identity provider. Credentials will not be extracted.");
+ filterChain.doFilter(servletRequest, servletResponse);
+ return;
+ }
+
+ if (credentialsAlreadyPresent()) {
+ logger.debug("Credentials already extracted for {}, skipping credentials extraction filter for {}",
+ SecurityContextHolder.getContext().getAuthentication().getPrincipal(),
+ identityProvider.getClass().getSimpleName());
+ filterChain.doFilter(servletRequest, servletResponse);
+ return;
+ }
+
+ logger.debug("Attempting to extract user credentials using {}", identityProvider.getClass().getSimpleName());
+
+ try {
+ AuthenticationRequest authenticationRequest = identityProvider.extractCredentials((HttpServletRequest)servletRequest);
+ if (authenticationRequest != null) {
+ Authentication authentication = new AuthenticationRequestToken(authenticationRequest, identityProvider.getClass(), servletRequest.getRemoteAddr());
+ logger.debug("Adding credentials claim to SecurityContext to be authenticated. Credentials extracted by {}: {}",
+ identityProvider.getClass().getSimpleName(),
+ authenticationRequest);
+ SecurityContextHolder.getContext().setAuthentication(authentication);
+ // This filter's job, which is merely to search for and extract an identity claim, is done.
+ // The actual authentication of the identity claim will be handled by a corresponding IdentityAuthenticationProvider
+ }
+ } catch (Exception e) {
+ logger.debug("Exception occurred while extracting credentials:", e);
+ }
+
+ filterChain.doFilter(servletRequest, servletResponse);
+ }
+
+ private boolean credentialsAlreadyPresent() {
+ return SecurityContextHolder.getContext().getAuthentication() != null;
+ }
+}
http://git-wip-us.apache.org/repos/asf/nifi-registry/blob/ef8ba127/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/LoginIdentityProviderFactory.java
----------------------------------------------------------------------
diff --git a/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/LoginIdentityProviderFactory.java b/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/LoginIdentityProviderFactory.java
deleted file mode 100644
index 434d881..0000000
--- a/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/LoginIdentityProviderFactory.java
+++ /dev/null
@@ -1,264 +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.registry.web.security.authentication;
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.nifi.registry.security.authentication.LoginIdentityProvider;
-import org.apache.nifi.registry.security.authentication.LoginIdentityProviderConfigurationContext;
-import org.apache.nifi.registry.security.authentication.LoginIdentityProviderLookup;
-import org.apache.nifi.registry.security.authentication.annotation.LoginIdentityProviderContext;
-import org.apache.nifi.registry.extension.ExtensionManager;
-import org.apache.nifi.registry.properties.NiFiRegistryProperties;
-import org.apache.nifi.registry.security.authentication.generated.IdentityProviders;
-import org.apache.nifi.registry.security.authentication.generated.Property;
-import org.apache.nifi.registry.security.authentication.generated.Provider;
-import org.apache.nifi.registry.security.util.XmlUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.DisposableBean;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.xml.sax.SAXException;
-
-import javax.xml.XMLConstants;
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.JAXBElement;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Unmarshaller;
-import javax.xml.stream.XMLStreamReader;
-import javax.xml.transform.stream.StreamSource;
-import javax.xml.validation.Schema;
-import javax.xml.validation.SchemaFactory;
-import java.io.File;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Field;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.HashMap;
-import java.util.Map;
-
-@Configuration
-public class LoginIdentityProviderFactory implements LoginIdentityProviderLookup, DisposableBean {
-
- private static final Logger logger = LoggerFactory.getLogger(LoginIdentityProviderFactory.class);
- private static final String LOGIN_IDENTITY_PROVIDERS_XSD = "/identity-providers.xsd";
- private static final String JAXB_GENERATED_PATH = "org.apache.nifi.registry.security.authentication.generated";
- private static final JAXBContext JAXB_CONTEXT = initializeJaxbContext();
-
- private static JAXBContext initializeJaxbContext() {
- try {
- return JAXBContext.newInstance(JAXB_GENERATED_PATH, LoginIdentityProviderFactory.class.getClassLoader());
- } catch (JAXBException e) {
- throw new RuntimeException("Unable to create JAXBContext.");
- }
- }
-
- private NiFiRegistryProperties properties;
- private ExtensionManager extensionManager;
- private LoginIdentityProvider loginIdentityProvider;
- private final Map<String, LoginIdentityProvider> loginIdentityProviders = new HashMap<>();
-
- @Autowired
- public LoginIdentityProviderFactory(final NiFiRegistryProperties properties, final ExtensionManager extensionManager) {
- this.properties = properties;
- this.extensionManager = extensionManager;
-
- if (this.properties == null) {
- throw new IllegalStateException("NiFiRegistryProperties cannot be null");
- }
-
- if (this.extensionManager == null) {
- throw new IllegalStateException("ExtensionManager cannot be null");
- }
- }
-
- @Override
- public LoginIdentityProvider getLoginIdentityProvider(String identifier) {
- return loginIdentityProviders.get(identifier);
- }
-
- @Bean
- public LoginIdentityProvider getLoginIdentityProvider() throws Exception {
- if (loginIdentityProvider == null) {
- // look up the login identity provider to use
- final String loginIdentityProviderIdentifier = properties.getProperty(NiFiRegistryProperties.SECURITY_IDENTITY_PROVIDER);
-
- // ensure the login identity provider class name was specified
- if (StringUtils.isNotBlank(loginIdentityProviderIdentifier)) {
- final IdentityProviders loginIdentityProviderConfiguration = loadLoginIdentityProvidersConfiguration();
-
- // create each login identity provider
- for (final Provider provider : loginIdentityProviderConfiguration.getProvider()) {
- loginIdentityProviders.put(provider.getIdentifier(), createLoginIdentityProvider(provider.getIdentifier(), provider.getClazz()));
- }
-
- // configure each login identity provider
- for (final Provider provider : loginIdentityProviderConfiguration.getProvider()) {
- final LoginIdentityProvider instance = loginIdentityProviders.get(provider.getIdentifier());
- instance.onConfigured(loadLoginIdentityProviderConfiguration(provider));
- }
-
- // get the login identity provider instance
- loginIdentityProvider = getLoginIdentityProvider(loginIdentityProviderIdentifier);
-
- // ensure it was found
- if (loginIdentityProvider == null) {
- throw new Exception(String.format("The specified login identity provider '%s' could not be found.", loginIdentityProviderIdentifier));
- }
- }
- }
-
- return loginIdentityProvider;
- }
-
- @Override
- public void destroy() throws Exception {
- if (loginIdentityProviders != null) {
- loginIdentityProviders.entrySet().stream().forEach(e -> e.getValue().preDestruction());
- }
- }
-
- private IdentityProviders loadLoginIdentityProvidersConfiguration() throws Exception {
- final File loginIdentityProvidersConfigurationFile = properties.getIdentityProviderConfigurationFile();
-
- // load the users from the specified file
- if (loginIdentityProvidersConfigurationFile.exists()) {
- try {
- // find the schema
- final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
- final Schema schema = schemaFactory.newSchema(IdentityProviders.class.getResource(LOGIN_IDENTITY_PROVIDERS_XSD));
-
- // attempt to unmarshal
- XMLStreamReader xsr = XmlUtils.createSafeReader(new StreamSource(loginIdentityProvidersConfigurationFile));
- final Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
- unmarshaller.setSchema(schema);
- final JAXBElement<IdentityProviders> element = unmarshaller.unmarshal(xsr, IdentityProviders.class);
- return element.getValue();
- } catch (SAXException | JAXBException e) {
- throw new Exception("Unable to load the login identity provider configuration file at: " + loginIdentityProvidersConfigurationFile.getAbsolutePath());
- }
- } else {
- throw new Exception("Unable to find the login identity provider configuration file at " + loginIdentityProvidersConfigurationFile.getAbsolutePath());
- }
- }
-
- private LoginIdentityProvider createLoginIdentityProvider(final String identifier, final String loginIdentityProviderClassName) throws Exception {
- final LoginIdentityProvider instance;
-
- final ClassLoader classLoader = extensionManager.getExtensionClassLoader(loginIdentityProviderClassName);
- if (classLoader == null) {
- throw new IllegalStateException("Extension not found in any of the configured class loaders: " + loginIdentityProviderClassName);
- }
-
- // attempt to load the class
- Class<?> rawLoginIdentityProviderClass = Class.forName(loginIdentityProviderClassName, true, classLoader);
- Class<? extends LoginIdentityProvider> loginIdentityProviderClass = rawLoginIdentityProviderClass.asSubclass(LoginIdentityProvider.class);
-
- // otherwise create a new instance
- Constructor constructor = loginIdentityProviderClass.getConstructor();
- instance = (LoginIdentityProvider) constructor.newInstance();
-
- // method injection
- performMethodInjection(instance, loginIdentityProviderClass);
-
- // field injection
- performFieldInjection(instance, loginIdentityProviderClass);
-
- // call post construction lifecycle event
- instance.initialize(new StandardLoginIdentityProviderInitializationContext(identifier, this));
-
- return instance;
- }
-
- private LoginIdentityProviderConfigurationContext loadLoginIdentityProviderConfiguration(final Provider provider) {
- final Map<String, String> providerProperties = new HashMap<>();
-
- for (final Property property : provider.getProperty()) {
- providerProperties.put(property.getName(), property.getValue());
- }
-
- return new StandardLoginIdentityProviderConfigurationContext(provider.getIdentifier(), providerProperties);
- }
-
- private void performMethodInjection(final LoginIdentityProvider instance, final Class loginIdentityProviderClass)
- throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
-
- for (final Method method : loginIdentityProviderClass.getMethods()) {
- if (method.isAnnotationPresent(LoginIdentityProviderContext.class)) {
- // make the method accessible
- final boolean isAccessible = method.isAccessible();
- method.setAccessible(true);
-
- try {
- final Class<?>[] argumentTypes = method.getParameterTypes();
-
- // look for setters (single argument)
- if (argumentTypes.length == 1) {
- final Class<?> argumentType = argumentTypes[0];
-
- // look for well known types
- if (NiFiRegistryProperties.class.isAssignableFrom(argumentType)) {
- // nifi properties injection
- method.invoke(instance, properties);
- }
- }
- } finally {
- method.setAccessible(isAccessible);
- }
- }
- }
-
- final Class parentClass = loginIdentityProviderClass.getSuperclass();
- if (parentClass != null && LoginIdentityProvider.class.isAssignableFrom(parentClass)) {
- performMethodInjection(instance, parentClass);
- }
- }
-
- private void performFieldInjection(final LoginIdentityProvider instance, final Class loginIdentityProviderClass) throws IllegalArgumentException, IllegalAccessException {
- for (final Field field : loginIdentityProviderClass.getDeclaredFields()) {
- if (field.isAnnotationPresent(LoginIdentityProviderContext.class)) {
- // make the method accessible
- final boolean isAccessible = field.isAccessible();
- field.setAccessible(true);
-
- try {
- // get the type
- final Class<?> fieldType = field.getType();
-
- // only consider this field if it isn't set yet
- if (field.get(instance) == null) {
- // look for well known types
- if (NiFiRegistryProperties.class.isAssignableFrom(fieldType)) {
- // nifi properties injection
- field.set(instance, properties);
- }
- }
-
- } finally {
- field.setAccessible(isAccessible);
- }
- }
- }
-
- final Class parentClass = loginIdentityProviderClass.getSuperclass();
- if (parentClass != null && LoginIdentityProvider.class.isAssignableFrom(parentClass)) {
- performFieldInjection(instance, parentClass);
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/nifi-registry/blob/ef8ba127/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/NiFiAnonymousUserFilter.java
----------------------------------------------------------------------
diff --git a/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/NiFiAnonymousUserFilter.java b/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/NiFiAnonymousUserFilter.java
deleted file mode 100644
index a27fd18..0000000
--- a/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/NiFiAnonymousUserFilter.java
+++ /dev/null
@@ -1,40 +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.registry.web.security.authentication;
-
-import org.apache.nifi.registry.security.authorization.user.NiFiUserDetails;
-import org.apache.nifi.registry.security.authorization.user.StandardNiFiUser;
-import org.apache.nifi.registry.web.security.authentication.token.NiFiAuthenticationToken;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.web.authentication.AnonymousAuthenticationFilter;
-
-import javax.servlet.http.HttpServletRequest;
-
-public class NiFiAnonymousUserFilter extends AnonymousAuthenticationFilter {
-
- private static final String ANONYMOUS_KEY = "anonymousNifiKey";
-
- public NiFiAnonymousUserFilter() {
- super(ANONYMOUS_KEY);
- }
-
- @Override
- protected Authentication createAuthentication(HttpServletRequest request) {
- return new NiFiAuthenticationToken(new NiFiUserDetails(StandardNiFiUser.ANONYMOUS));
- }
-
-}
http://git-wip-us.apache.org/repos/asf/nifi-registry/blob/ef8ba127/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/NiFiAuthenticationFilter.java
----------------------------------------------------------------------
diff --git a/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/NiFiAuthenticationFilter.java b/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/NiFiAuthenticationFilter.java
deleted file mode 100644
index 24af504..0000000
--- a/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/NiFiAuthenticationFilter.java
+++ /dev/null
@@ -1,156 +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.registry.web.security.authentication;
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.nifi.registry.security.authorization.user.NiFiUserUtils;
-import org.apache.nifi.registry.properties.NiFiRegistryProperties;
-import org.apache.nifi.registry.web.security.authentication.exception.InvalidAuthenticationException;
-import org.apache.nifi.registry.web.security.authentication.exception.UntrustedProxyException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.security.authentication.AuthenticationManager;
-import org.springframework.security.authentication.AuthenticationServiceException;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.AuthenticationException;
-import org.springframework.security.core.context.SecurityContextHolder;
-import org.springframework.web.filter.GenericFilterBean;
-
-import javax.servlet.FilterChain;
-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.io.PrintWriter;
-
-/**
- *
- */
-public abstract class NiFiAuthenticationFilter extends GenericFilterBean {
-
- private static final Logger log = LoggerFactory.getLogger(NiFiAuthenticationFilter.class);
-
- private AuthenticationManager authenticationManager;
- private NiFiRegistryProperties properties;
-
- @Override
- public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
- final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
- if (log.isDebugEnabled()) {
- log.debug("Checking secure context token: " + authentication);
- }
-
- if (requiresAuthentication((HttpServletRequest) request)) {
- authenticate((HttpServletRequest) request, (HttpServletResponse) response, chain);
- } else {
- chain.doFilter(request, response);
- }
-
- }
-
- private boolean requiresAuthentication(final HttpServletRequest request) {
- return NiFiUserUtils.getNiFiUser() == null;
- }
-
- private void authenticate(final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) throws IOException, ServletException {
- String dnChain = null;
- try {
- final Authentication authenticationRequest = attemptAuthentication(request);
- if (authenticationRequest != null) {
- // log the request attempt - response details will be logged later
- log.info(String.format("Attempting request for (%s) %s %s (source ip: %s)", authenticationRequest.toString(), request.getMethod(),
- request.getRequestURL().toString(), request.getRemoteAddr()));
-
- // attempt to authorize the user
- final Authentication authenticated = authenticationManager.authenticate(authenticationRequest);
- successfulAuthorization(request, response, authenticated);
- }
-
- // continue
- chain.doFilter(request, response);
- } catch (final AuthenticationException ae) {
- // invalid authentication - always error out
- unsuccessfulAuthorization(request, response, ae);
- }
- }
-
- /**
- * Attempt to extract an authentication attempt from the specified request.
- *
- * @param request The request
- * @return The authentication attempt or null if none is found int he request
- */
- public abstract Authentication attemptAuthentication(HttpServletRequest request);
-
- protected void successfulAuthorization(HttpServletRequest request, HttpServletResponse response, Authentication authResult) {
- log.info("Authentication success for " + authResult);
-
- SecurityContextHolder.getContext().setAuthentication(authResult);
- ProxiedEntitiesUtils.successfulAuthorization(request, response, authResult);
- }
-
- protected void unsuccessfulAuthorization(HttpServletRequest request, HttpServletResponse response, AuthenticationException ae) throws IOException {
- // populate the response
- ProxiedEntitiesUtils.unsuccessfulAuthorization(request, response, ae);
-
- // set the response status
- response.setContentType("text/plain");
-
- // write the response message
- PrintWriter out = response.getWriter();
-
- // use the type of authentication exception to determine the response code
- if (ae instanceof InvalidAuthenticationException) {
- response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
- out.println(ae.getMessage());
- } else if (ae instanceof UntrustedProxyException) {
- response.setStatus(HttpServletResponse.SC_FORBIDDEN);
- out.println(ae.getMessage());
- } else if (ae instanceof AuthenticationServiceException) {
- log.error(String.format("Unable to authorize: %s", ae.getMessage()), ae);
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- out.println(String.format("Unable to authorize: %s", ae.getMessage()));
- } else {
- log.error(String.format("Unable to authorize: %s", ae.getMessage()), ae);
- response.setStatus(HttpServletResponse.SC_FORBIDDEN);
- out.println("Access is denied.");
- }
-
- // log the failure
- log.warn(String.format("Rejecting access to web api: %s", ae.getMessage()));
-
- // optionally log the stack trace
- if (log.isDebugEnabled()) {
- log.debug(StringUtils.EMPTY, ae);
- }
- }
-
- @Override
- public void destroy() {
- }
-
- public void setAuthenticationManager(AuthenticationManager authenticationManager) {
- this.authenticationManager = authenticationManager;
- }
-
- public void setProperties(NiFiRegistryProperties properties) {
- this.properties = properties;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/nifi-registry/blob/ef8ba127/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/NiFiAuthenticationProvider.java
----------------------------------------------------------------------
diff --git a/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/NiFiAuthenticationProvider.java b/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/NiFiAuthenticationProvider.java
deleted file mode 100644
index 5617e0e..0000000
--- a/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/NiFiAuthenticationProvider.java
+++ /dev/null
@@ -1,84 +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.registry.web.security.authentication;
-
-import org.apache.nifi.registry.security.authorization.Authorizer;
-import org.apache.nifi.registry.security.authorization.Group;
-import org.apache.nifi.registry.security.authorization.ManagedAuthorizer;
-import org.apache.nifi.registry.security.authorization.UserAndGroups;
-import org.apache.nifi.registry.security.authorization.UserGroupProvider;
-import org.apache.nifi.registry.properties.NiFiRegistryProperties;
-import org.apache.nifi.registry.properties.util.IdentityMapping;
-import org.apache.nifi.registry.properties.util.IdentityMappingUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.security.authentication.AuthenticationProvider;
-
-import java.util.Collections;
-import java.util.List;
-import java.util.Set;
-import java.util.stream.Collectors;
-
-/**
- * Base AuthenticationProvider that provides common functionality to mapping identities.
- */
-public abstract class NiFiAuthenticationProvider implements AuthenticationProvider {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(NiFiAuthenticationProvider.class);
-
- private NiFiRegistryProperties properties;
- private Authorizer authorizer;
- private List<IdentityMapping> mappings;
-
- /**
- * @param properties the NiFiProperties instance
- */
- public NiFiAuthenticationProvider(final NiFiRegistryProperties properties, final Authorizer authorizer) {
- this.properties = properties;
- this.mappings = Collections.unmodifiableList(IdentityMappingUtil.getIdentityMappings(properties));
- this.authorizer = authorizer;
- }
-
- public List<IdentityMapping> getMappings() {
- return mappings;
- }
-
- protected String mapIdentity(final String identity) {
- return IdentityMappingUtil.mapIdentity(identity, mappings);
- }
-
- protected Set<String> getUserGroups(final String identity) {
- return getUserGroups(authorizer, identity);
- }
-
- protected static Set<String> getUserGroups(final Authorizer authorizer, final String userIdentity) {
- if (authorizer instanceof ManagedAuthorizer) {
- final ManagedAuthorizer managedAuthorizer = (ManagedAuthorizer) authorizer;
- final UserGroupProvider userGroupProvider = managedAuthorizer.getAccessPolicyProvider().getUserGroupProvider();
- final UserAndGroups userAndGroups = userGroupProvider.getUserAndGroups(userIdentity);
- final Set<Group> userGroups = userAndGroups.getGroups();
-
- if (userGroups == null || userGroups.isEmpty()) {
- return Collections.EMPTY_SET;
- } else {
- return userAndGroups.getGroups().stream().map(group -> group.getName()).collect(Collectors.toSet());
- }
- } else {
- return null;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/nifi-registry/blob/ef8ba127/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/NiFiAuthenticationRequestToken.java
----------------------------------------------------------------------
diff --git a/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/NiFiAuthenticationRequestToken.java b/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/NiFiAuthenticationRequestToken.java
deleted file mode 100644
index 3da95c5..0000000
--- a/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/NiFiAuthenticationRequestToken.java
+++ /dev/null
@@ -1,41 +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.registry.web.security.authentication;
-
-import org.springframework.security.authentication.AbstractAuthenticationToken;
-
-/**
- * Base class for authentication request tokens in NiFI.
- */
-public abstract class NiFiAuthenticationRequestToken extends AbstractAuthenticationToken {
-
- private final String clientAddress;
-
- /**
- * @param clientAddress The address of the client making the request
- */
- public NiFiAuthenticationRequestToken(final String clientAddress) {
- super(null);
- setAuthenticated(false);
- this.clientAddress = clientAddress;
- }
-
- public String getClientAddress() {
- return clientAddress;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/nifi-registry/blob/ef8ba127/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/ProxiedEntitiesUtils.java
----------------------------------------------------------------------
diff --git a/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/ProxiedEntitiesUtils.java b/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/ProxiedEntitiesUtils.java
deleted file mode 100644
index 05687f8..0000000
--- a/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/ProxiedEntitiesUtils.java
+++ /dev/null
@@ -1,163 +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.registry.web.security.authentication;
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.nifi.registry.security.authorization.user.NiFiUser;
-import org.apache.nifi.registry.security.authorization.user.NiFiUserUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.AuthenticationException;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.stream.Collectors;
-
-/**
- *
- */
-public class ProxiedEntitiesUtils {
- private static final Logger logger = LoggerFactory.getLogger(ProxiedEntitiesUtils.class);
-
- 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 String GT = ">";
- private static final String ESCAPED_GT = "\\\\>";
- private static final String LT = "<";
- private static final String ESCAPED_LT = "\\\\<";
-
- private static final String ANONYMOUS_CHAIN = "<>";
-
- /**
- * 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 LT + sanitizeDn(dn) + GT;
- }
-
- /**
- * If a user provides a DN with the sequence '><', they could escape the tokenization process and impersonate another user.
- * <p>
- * Example:
- * <p>
- * Provided DN: {@code jdoe><alopresto} -> {@code <jdoe><alopresto><proxy...>} would allow the user to impersonate jdoe
- *
- * @param rawDn the unsanitized DN
- * @return the sanitized DN
- */
- private static String sanitizeDn(String rawDn) {
- if (StringUtils.isEmpty(rawDn)) {
- return rawDn;
- } else {
- String sanitizedDn = rawDn.replaceAll(GT, ESCAPED_GT).replaceAll(LT, ESCAPED_LT);
- if (!sanitizedDn.equals(rawDn)) {
- logger.warn("The provided DN [" + rawDn + "] contained dangerous characters that were escaped to [" + sanitizedDn + "]");
- }
- return sanitizedDn;
- }
- }
-
- /**
- * Reconstitutes the original DN from the sanitized version passed in the proxy chain.
- * <p>
- * Example:
- * <p>
- * {@code alopresto\>\<proxy1} -> {@code alopresto><proxy1}
- *
- * @param sanitizedDn the sanitized DN
- * @return the original DN
- */
- private static String unsanitizeDn(String sanitizedDn) {
- if (StringUtils.isEmpty(sanitizedDn)) {
- return sanitizedDn;
- } else {
- String unsanitizedDn = sanitizedDn.replaceAll(ESCAPED_GT, GT).replaceAll(ESCAPED_LT, LT);
- if (!unsanitizedDn.equals(sanitizedDn)) {
- logger.warn("The provided DN [" + sanitizedDn + "] had been escaped, and was reconstituted to the dangerous DN [" + unsanitizedDn + "]");
- }
- return unsanitizedDn;
- }
- }
-
- /**
- * Tokenizes the specified proxy chain.
- *
- * @param rawProxyChain raw chain
- * @return tokenized proxy chain
- */
- public static List<String> tokenizeProxiedEntitiesChain(String rawProxyChain) {
- final List<String> proxyChain = new ArrayList<>();
- if (!StringUtils.isEmpty(rawProxyChain)) {
- // Split the String on the >< token
- List<String> elements = Arrays.asList(StringUtils.splitByWholeSeparatorPreserveAllTokens(rawProxyChain, "><"));
-
- // Unsanitize each DN and collect back
- elements = elements.stream().map(ProxiedEntitiesUtils::unsanitizeDn).collect(Collectors.toList());
-
- // Remove the leading < from the first element
- elements.set(0, elements.get(0).replaceFirst(LT, ""));
-
- // Remove the trailing > from the last element
- int last = elements.size() - 1;
- String lastElement = elements.get(last);
- if (lastElement.endsWith(GT)) {
- elements.set(last, lastElement.substring(0, lastElement.length() - 1));
- }
-
- proxyChain.addAll(elements);
- }
-
- return proxyChain;
- }
-
- /**
- * Builds the proxy chain for the specified user.
- *
- * @param user The current user
- * @return The proxy chain for that user in String form
- */
- public static String buildProxiedEntitiesChainString(final NiFiUser user) {
- // calculate the dn chain
- List<String> proxyChain = NiFiUserUtils.buildProxiedEntitiesChain(user);
- if (proxyChain.isEmpty()) {
- return ANONYMOUS_CHAIN;
- }
- proxyChain = proxyChain.stream().map(ProxiedEntitiesUtils::formatProxyDn).collect(Collectors.toList());
- return StringUtils.join(proxyChain, "");
- }
-
- 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-registry/blob/ef8ba127/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/StandardLoginIdentityProviderConfigurationContext.java
----------------------------------------------------------------------
diff --git a/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/StandardLoginIdentityProviderConfigurationContext.java b/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/StandardLoginIdentityProviderConfigurationContext.java
deleted file mode 100644
index 3a9cdd6..0000000
--- a/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/StandardLoginIdentityProviderConfigurationContext.java
+++ /dev/null
@@ -1,52 +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.registry.web.security.authentication;
-
-import org.apache.nifi.registry.security.authentication.LoginIdentityProviderConfigurationContext;
-
-import java.util.Collections;
-import java.util.Map;
-
-/**
- *
- */
-public class StandardLoginIdentityProviderConfigurationContext implements LoginIdentityProviderConfigurationContext {
-
- private final String identifier;
- private final Map<String, String> properties;
-
- public StandardLoginIdentityProviderConfigurationContext(String identifier, Map<String, String> properties) {
- this.identifier = identifier;
- this.properties = properties;
- }
-
- @Override
- public String getIdentifier() {
- return identifier;
- }
-
- @Override
- public Map<String, String> getProperties() {
- return Collections.unmodifiableMap(properties);
- }
-
- @Override
- public String getProperty(String property) {
- return properties.get(property);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/nifi-registry/blob/ef8ba127/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/StandardLoginIdentityProviderInitializationContext.java
----------------------------------------------------------------------
diff --git a/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/StandardLoginIdentityProviderInitializationContext.java b/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/StandardLoginIdentityProviderInitializationContext.java
deleted file mode 100644
index e8fba2e..0000000
--- a/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/StandardLoginIdentityProviderInitializationContext.java
+++ /dev/null
@@ -1,45 +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.registry.web.security.authentication;
-
-import org.apache.nifi.registry.security.authentication.LoginIdentityProviderInitializationContext;
-import org.apache.nifi.registry.security.authentication.LoginIdentityProviderLookup;
-
-/**
- *
- */
-public class StandardLoginIdentityProviderInitializationContext implements LoginIdentityProviderInitializationContext {
-
- private final String identifier;
- private final LoginIdentityProviderLookup lookup;
-
- public StandardLoginIdentityProviderInitializationContext(String identifier, final LoginIdentityProviderLookup lookup) {
- this.identifier = identifier;
- this.lookup = lookup;
- }
-
- @Override
- public String getIdentifier() {
- return identifier;
- }
-
- @Override
- public LoginIdentityProviderLookup getAuthorityProviderLookup() {
- return lookup;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/nifi-registry/blob/ef8ba127/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/exception/UntrustedProxyException.java
----------------------------------------------------------------------
diff --git a/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/exception/UntrustedProxyException.java b/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/exception/UntrustedProxyException.java
index 6245ac2..82570a3 100644
--- a/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/exception/UntrustedProxyException.java
+++ b/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/exception/UntrustedProxyException.java
@@ -18,9 +18,6 @@ package org.apache.nifi.registry.web.security.authentication.exception;
import org.springframework.security.core.AuthenticationException;
-/**
- *
- */
public class UntrustedProxyException extends AuthenticationException {
public UntrustedProxyException(String msg) {
http://git-wip-us.apache.org/repos/asf/nifi-registry/blob/ef8ba127/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/jwt/JwtAuthenticationFilter.java
----------------------------------------------------------------------
diff --git a/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/jwt/JwtAuthenticationFilter.java b/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/jwt/JwtAuthenticationFilter.java
deleted file mode 100644
index 1e5c194..0000000
--- a/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/jwt/JwtAuthenticationFilter.java
+++ /dev/null
@@ -1,58 +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.registry.web.security.authentication.jwt;
-
-import org.apache.commons.lang3.StringUtils;
-
-import org.apache.nifi.registry.web.security.authentication.NiFiAuthenticationFilter;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.security.core.Authentication;
-
-import javax.servlet.http.HttpServletRequest;
-
-/**
- */
-public class JwtAuthenticationFilter extends NiFiAuthenticationFilter {
-
- private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);
-
- public static final String AUTHORIZATION = "Authorization";
- public static final String BEARER = "Bearer ";
-
- @Override
- public Authentication attemptAuthentication(final HttpServletRequest request) {
- // only support jwt login when running securely
- if (!request.isSecure()) {
- return null;
- }
-
- // TODO: Refactor request header extraction logic to shared utility as it is duplicated in AccessResource
-
- // get the principal out of the user token
- final String authorization = request.getHeader(AUTHORIZATION);
-
- // if there is no authorization header, we don't know the user
- if (authorization == null || !StringUtils.startsWith(authorization, BEARER)) {
- return null;
- } else {
- // Extract the Base64 encoded token from the Authorization header
- final String token = StringUtils.substringAfterLast(authorization, " ");
- return new JwtAuthenticationRequestToken(token, request.getRemoteAddr());
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/nifi-registry/blob/ef8ba127/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/jwt/JwtAuthenticationProvider.java
----------------------------------------------------------------------
diff --git a/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/jwt/JwtAuthenticationProvider.java b/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/jwt/JwtAuthenticationProvider.java
deleted file mode 100644
index 2247923..0000000
--- a/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/jwt/JwtAuthenticationProvider.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.registry.web.security.authentication.jwt;
-
-import io.jsonwebtoken.JwtException;
-import org.apache.nifi.registry.security.authorization.Authorizer;
-import org.apache.nifi.registry.security.authorization.user.NiFiUser;
-import org.apache.nifi.registry.security.authorization.user.NiFiUserDetails;
-import org.apache.nifi.registry.security.authorization.user.StandardNiFiUser;
-import org.apache.nifi.registry.properties.NiFiRegistryProperties;
-import org.apache.nifi.registry.web.security.authentication.exception.InvalidAuthenticationException;
-import org.apache.nifi.registry.web.security.authentication.NiFiAuthenticationProvider;
-import org.apache.nifi.registry.web.security.authentication.token.NiFiAuthenticationToken;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.AuthenticationException;
-import org.springframework.stereotype.Component;
-
-/**
- *
- */
-@Component
-public class JwtAuthenticationProvider extends NiFiAuthenticationProvider {
-
- private final JwtService jwtService;
-
- @Autowired
- public JwtAuthenticationProvider(JwtService jwtService, NiFiRegistryProperties nifiProperties, Authorizer authorizer) {
- super(nifiProperties, authorizer);
- this.jwtService = jwtService;
- }
-
- @Override
- public Authentication authenticate(Authentication authentication) throws AuthenticationException {
- final JwtAuthenticationRequestToken request = (JwtAuthenticationRequestToken) authentication;
-
- try {
- final String jwtPrincipal = jwtService.getAuthenticationFromToken(request.getToken());
- final String mappedIdentity = mapIdentity(jwtPrincipal);
- final NiFiUser user = new StandardNiFiUser.Builder()
- .identity(mappedIdentity)
- .groups(getUserGroups(mappedIdentity))
- .clientAddress(request.getClientAddress())
- .build();
- return new NiFiAuthenticationToken(new NiFiUserDetails(user));
- } catch (JwtException e) {
- throw new InvalidAuthenticationException(e.getMessage(), e);
- }
- }
-
- @Override
- public boolean supports(Class<?> authentication) {
- return JwtAuthenticationRequestToken.class.isAssignableFrom(authentication);
- }
-}
http://git-wip-us.apache.org/repos/asf/nifi-registry/blob/ef8ba127/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/jwt/JwtAuthenticationRequestToken.java
----------------------------------------------------------------------
diff --git a/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/jwt/JwtAuthenticationRequestToken.java b/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/jwt/JwtAuthenticationRequestToken.java
deleted file mode 100644
index e8af9ff..0000000
--- a/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/jwt/JwtAuthenticationRequestToken.java
+++ /dev/null
@@ -1,60 +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.registry.web.security.authentication.jwt;
-
-
-import org.apache.nifi.registry.web.security.authentication.NiFiAuthenticationRequestToken;
-
-/**
- * This is an authentication request with a given JWT token.
- */
-public class JwtAuthenticationRequestToken extends NiFiAuthenticationRequestToken {
-
- private final String token;
-
- /**
- * Creates a representation of the jwt authentication request for a user.
- *
- * @param token The unique token for this user
- * @param clientAddress the address of the client making the request
- */
- public JwtAuthenticationRequestToken(final String token, final String clientAddress) {
- super(clientAddress);
- setAuthenticated(false);
- this.token = token;
- }
-
- @Override
- public Object getCredentials() {
- return null;
- }
-
- @Override
- public Object getPrincipal() {
- return token;
- }
-
- public String getToken() {
- return token;
- }
-
- @Override
- public String toString() {
- return "<JWT token>";
- }
-
-}
http://git-wip-us.apache.org/repos/asf/nifi-registry/blob/ef8ba127/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/jwt/JwtIdentityProvider.java
----------------------------------------------------------------------
diff --git a/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/jwt/JwtIdentityProvider.java b/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/jwt/JwtIdentityProvider.java
new file mode 100644
index 0000000..9592c2b
--- /dev/null
+++ b/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/security/authentication/jwt/JwtIdentityProvider.java
@@ -0,0 +1,76 @@
+/*
+ * 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.registry.web.security.authentication.jwt;
+
+import io.jsonwebtoken.JwtException;
+import org.apache.nifi.registry.properties.NiFiRegistryProperties;
+import org.apache.nifi.registry.security.authentication.AuthenticationRequest;
+import org.apache.nifi.registry.security.authentication.AuthenticationResponse;
+import org.apache.nifi.registry.security.authentication.BearerAuthIdentityProvider;
+import org.apache.nifi.registry.security.authentication.IdentityProvider;
+import org.apache.nifi.registry.security.authentication.IdentityProviderConfigurationContext;
+import org.apache.nifi.registry.security.authentication.exception.IdentityAccessException;
+import org.apache.nifi.registry.security.authentication.exception.InvalidCredentialsException;
+import org.apache.nifi.registry.security.authorization.Authorizer;
+import org.apache.nifi.registry.security.exception.SecurityProviderCreationException;
+import org.apache.nifi.registry.security.exception.SecurityProviderDestructionException;
+import org.apache.nifi.registry.web.security.authentication.exception.InvalidAuthenticationException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.util.concurrent.TimeUnit;
+
+@Component
+public class JwtIdentityProvider extends BearerAuthIdentityProvider implements IdentityProvider {
+
+ private static final Logger logger = LoggerFactory.getLogger(JwtIdentityProvider.class);
+
+ private static final String issuer = JwtIdentityProvider.class.getSimpleName();
+
+ private static final long expiration = TimeUnit.MILLISECONDS.convert(12, TimeUnit.HOURS);
+
+ private final JwtService jwtService;
+
+ @Autowired
+ public JwtIdentityProvider(JwtService jwtService, NiFiRegistryProperties nifiProperties, Authorizer authorizer) {
+ this.jwtService = jwtService;
+ }
+
+ @Override
+ public AuthenticationResponse authenticate(AuthenticationRequest authenticationRequest) throws InvalidCredentialsException, IdentityAccessException {
+ try {
+ String jwtAuthToken = (String) authenticationRequest.getCredentials();
+ final String jwtPrincipal = jwtService.getAuthenticationFromToken(jwtAuthToken);
+
+ return new AuthenticationResponse(jwtPrincipal, jwtPrincipal, expiration, issuer);
+ } catch (ClassCastException e) {
+ // token String in credentials Object
+ return null;
+ } catch (JwtException e) {
+ throw new InvalidAuthenticationException(e.getMessage(), e);
+ }
+ }
+
+ @Override
+ public void onConfigured(IdentityProviderConfigurationContext configurationContext) throws SecurityProviderCreationException {}
+
+ @Override
+ public void preDestruction() throws SecurityProviderDestructionException {}
+
+}