Cleanup TokenAuthRealm 75/101675/3
authorRobert Varga <robert.varga@pantheon.tech>
Fri, 1 Jul 2022 11:58:25 +0000 (13:58 +0200)
committerRobert Varga <robert.varga@pantheon.tech>
Fri, 1 Jul 2022 14:13:34 +0000 (16:13 +0200)
Use static import of requireNonNull(), do not perform blind casts
and inline single-use constants.

Change-Id: I9defff8f9809be9bddf5bd0d9c88561b698eeb58
Signed-off-by: Robert Varga <robert.varga@pantheon.tech>
aaa-shiro/impl/src/main/java/org/opendaylight/aaa/shiro/realm/TokenAuthRealm.java

index 4812925df1cce4e3b43860c453ce53bea1fcc5bd..4a6bcd57f9da7085eae6395014bca8302fe57913 100644 (file)
@@ -5,13 +5,13 @@
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
  * and is available at http://www.eclipse.org/legal/epl-v10.html
  */
-
 package org.opendaylight.aaa.shiro.realm;
 
+import static java.util.Objects.requireNonNull;
+
 import com.google.common.base.Strings;
 import java.util.List;
 import java.util.Map;
-import java.util.Objects;
 import org.apache.shiro.authc.AuthenticationException;
 import org.apache.shiro.authc.AuthenticationInfo;
 import org.apache.shiro.authc.AuthenticationToken;
@@ -34,40 +34,10 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * TokenAuthRealm is an adapter between the AAA shiro subsystem and the existing
- * <code>TokenAuth</code> mechanisms. Thus, one can enable use of
- * <code>IDMStore</code> and <code>IDMMDSALStore</code>.
+ * TokenAuthRealm is an adapter between the AAA shiro subsystem and the existing {@code TokenAuth} mechanisms. Thus, one
+ * can enable use of {@code IDMStore} and {@code IDMMDSALStore}.
  */
 public class TokenAuthRealm extends AuthorizingRealm {
-
-    /**
-     * The unique identifying name for <code>TokenAuthRealm</code>.
-     */
-    private static final String TOKEN_AUTH_REALM_DEFAULT_NAME = "TokenAuthRealm";
-
-    /**
-     * The message that is displayed if no <code>TokenAuth</code> interface is available yet.
-     */
-    private static final String AUTHENTICATION_SERVICE_UNAVAILABLE_MESSAGE =
-            "{\"error\":\"Authentication service unavailable\"}";
-
-    /**
-     * The message that is displayed if credentials are missing or malformed.
-     */
-    private static final String FATAL_ERROR_DECODING_CREDENTIALS = "{\"error\":\"Unable to decode credentials\"}";
-
-    /**
-     * The message that is displayed if non-Basic Auth is attempted.
-     */
-    private static final String FATAL_ERROR_BASIC_AUTH_ONLY
-            = "{\"error\":\"Only basic authentication is supported by TokenAuthRealm\"}";
-
-    /**
-     * The purposefully generic message displayed if <code>TokenAuth</code> is
-     * unable to validate the given credentials.
-     */
-    private static final String UNABLE_TO_AUTHENTICATE = "{\"error\":\"Could not authenticate\"}";
-
     private static final Logger LOG = LoggerFactory.getLogger(TokenAuthRealm.class);
 
     private final AuthenticationService authenticationService;
@@ -75,50 +45,40 @@ public class TokenAuthRealm extends AuthorizingRealm {
     private final TokenAuthenticators tokenAuthenticators;
 
     public TokenAuthRealm() {
-        super.setName(TOKEN_AUTH_REALM_DEFAULT_NAME);
-        authenticationService = Objects.requireNonNull(ThreadLocals.AUTH_SETVICE_TL.get());
+        authenticationService = requireNonNull(ThreadLocals.AUTH_SETVICE_TL.get());
         tokenStore = ThreadLocals.TOKEN_STORE_TL.get();
-        tokenAuthenticators = Objects.requireNonNull(ThreadLocals.TOKEN_AUTHENICATORS_TL.get());
+        tokenAuthenticators = requireNonNull(ThreadLocals.TOKEN_AUTHENICATORS_TL.get());
+        super.setName("TokenAuthRealm");
     }
 
-    /*
-     * (non-Javadoc)
-     *
-     * Roles are derived from <code>TokenAuth.authenticate()</code>. Shiro roles
-     * are identical to existing IDM roles.
+    /**
+     * {@inheritDoc}
      *
-     * @see
-     * org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache
-     * .shiro.subject.PrincipalCollection)
+     * <p>
+     * Roles are derived from {@code TokenAuth.authenticate()}. Shiro roles are identical to existing IDM roles.
      */
     @Override
     protected AuthorizationInfo doGetAuthorizationInfo(final PrincipalCollection principalCollection) {
-        final Object primaryPrincipal = principalCollection.getPrimaryPrincipal();
-        final ODLPrincipal odlPrincipal;
-        try {
-            odlPrincipal = (ODLPrincipal) primaryPrincipal;
-            return new SimpleAuthorizationInfo(odlPrincipal.getRoles());
-        } catch (ClassCastException e) {
-            LOG.error("Couldn't decode authorization request", e);
+        final var primaryPrincipal = principalCollection.getPrimaryPrincipal();
+        if (primaryPrincipal instanceof ODLPrincipal) {
+            return new SimpleAuthorizationInfo(((ODLPrincipal) primaryPrincipal).getRoles());
         }
+
+        LOG.error("Could not decode authorization request: {} is not a known principal type", primaryPrincipal);
         return new SimpleAuthorizationInfo();
     }
 
-    /*
-     * (non-Javadoc)
-     *
-     * Authenticates against any <code>TokenAuth</code> registered with the
-     * <code>ServiceLocator</code>
+    /**
+     * {@inheritDoc}
      *
-     * @see
-     * org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org
-     * .apache.shiro.authc.AuthenticationToken)
+     * <p>
+     * Authenticates against any {@code TokenAuth} registered with the {@code ServiceLocator}.
      */
     @Override
     protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken authenticationToken)
             throws AuthenticationException {
         if (authenticationToken == null) {
-            throw new AuthenticationException(FATAL_ERROR_DECODING_CREDENTIALS);
+            throw new AuthenticationException("{\"error\":\"Unable to decode credentials\"}");
         }
 
         final String username;
@@ -131,11 +91,11 @@ public class TokenAuthRealm extends AuthorizingRealm {
             domain = HeaderUtils.extractDomain(possiblyQualifiedUser);
             password = TokenUtils.extractPassword(authenticationToken);
         } catch (ClassCastException e) {
-            throw new AuthenticationException(FATAL_ERROR_BASIC_AUTH_ONLY, e);
+            throw new AuthenticationException(
+                "{\"error\":\"Only basic authentication is supported by TokenAuthRealm\"}", e);
         }
 
-        // if the password is empty, this is an OAuth2 request, not a Basic HTTP
-        // Auth request
+        // if the password is empty, this is an OAuth2 request, not a Basic HTTP Auth request
         if (!Strings.isNullOrEmpty(password)) {
             Map<String, List<String>> headers = HeaderUtils.formHeaders(username, password, domain);
             // iterate over <code>TokenAuth</code> implementations and
@@ -152,8 +112,9 @@ public class TokenAuthRealm extends AuthorizingRealm {
                         return new SimpleAuthenticationInfo(odlPrincipal, password.toCharArray(), getName());
                     }
                 } catch (AuthenticationException ae) {
-                    LOG.debug("Authentication attempt unsuccessful");
-                    throw new AuthenticationException(UNABLE_TO_AUTHENTICATE, ae);
+                    LOG.debug("Authentication attempt unsuccessful", ae);
+                    // Purposefully generic message
+                    throw new AuthenticationException("{\"error\":\"Could not authenticate\"}", ae);
                 }
             }
         }