super(msg, cause);
}
+ public AuthenticationException(Throwable throwable) {
+ super(throwable);
+ }
}
<build>
<plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <configuration>
+ <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+ </configuration>
+ </plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
package org.opendaylight.aaa.authenticator;
+import java.nio.charset.Charset;
+import java.util.Base64;
+import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import javax.servlet.http.HttpServletRequest;
-import java.nio.charset.Charset;
-import java.util.Base64;
-
/**
* AAA hook for <code>odl-jolokia</code> configured w/ <code>org.jolokia.authMode=service-all</code>.
*/
final String authorization = httpServletRequest.getHeader("Authorization");
if (authorization != null && authorization.startsWith("Basic")) {
final String base64Creds = authorization.substring("Basic".length()).trim();
- String credentials = new String(Base64.getDecoder().decode(base64Creds),
- Charset.forName("UTF-8"));
+ String credentials = new String(Base64.getDecoder().decode(base64Creds), Charset.forName("UTF-8"));
final String[] values = credentials.split(":", 2);
final Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken upt = new UsernamePasswordToken();
}
} catch (final ArrayIndexOutOfBoundsException e) {
LOG.trace("Jolokia Authentication attempt unsuccessful; formatting issue basic auth credentials");
- } catch(final AuthenticationException e) {
+ } catch (final AuthenticationException e) {
LOG.trace("Jolokia Authentication attempt unsuccessful; Couldn't authenticate the subject");
}
return false;
import org.opendaylight.aaa.api.TokenStore;
/**
- * Implementation of the mdsal AAA token store
+ * Implementation of the mdsal AAA token store.
*/
public class MdsalTokenStore implements AutoCloseable, TokenStore {
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
+import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
-import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.Consumes;
+import javax.ws.rs.Produces;
+import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
-import javax.ws.rs.Produces;
-import javax.ws.rs.WebApplicationException;
// Taken from https://memorynotfound.com/jaxrs-jersey-gson-serializer-deserializer/
@Provider
}
@Override
- public long getSize(T t, Class<?> type, Type genericType,
+ public long getSize(T type, Class<?> theClass, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return -1;
}
@Override
- public void writeTo(T t, Class<?> type, Type genericType, Annotation[] annotations,
+ public void writeTo(T type, Class<?> theClass, Type genericType, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream) throws IOException, WebApplicationException {
PrintWriter printWriter = new PrintWriter(entityStream);
try {
String json;
- if (ui.getQueryParameters().containsKey(PRETTY_PRINT)){
- json = prettyGson.toJson(t);
+ if (ui.getQueryParameters().containsKey(PRETTY_PRINT)) {
+ json = prettyGson.toJson(type);
} else {
- json = gson.toJson(t);
+ json = gson.toJson(type);
}
printWriter.write(json);
printWriter.flush();
* disabled by default in order to support workflows such as the feature
* <code>odl-restconf-noauth</code>.
*
+ * <p>
* The AAA service is enabled through installing the <code>odl-aaa-shiro</code>
* feature. The blueprint Provider in <code>aaa-shiro-act</code> enables AAA
* through the ServiceProxy, which in turn enables the AAAFilter.
*
+ * <p>
* ServiceProxy is a singleton; access to the ServiceProxy is granted through
* the <code>getInstance()</code> function.
*
* web,xml</a>
* @see <code>AAAFilter</code>
*/
-public class ServiceProxy {
+public final class ServiceProxy {
private static final Logger LOG = LoggerFactory.getLogger(ServiceProxy.class);
private AAAFilter filter;
/**
- * private for singleton pattern
+ * private for singleton pattern.
*/
private ServiceProxy() {
- final String INFO_MESSAGE = "Creating the ServiceProxy";
- LOG.info(INFO_MESSAGE);
+ final String infoMessage = "Creating the ServiceProxy";
+ LOG.info(infoMessage);
}
/**
- * @return ServiceProxy, a feature level singleton
+ * Returns the single instance.
+ *
+ * @return ServiceProxy, a feature level singleton.
*/
public static ServiceProxy getInstance() {
return instance;
/**
* Extract whether the service is enabled.
*
- * @param filter
+ * @param aaaFilter
* register an optional Filter for callback if enable state
* changes
* @return Whether the service is enabled
*/
- public synchronized boolean getEnabled(final AAAFilter filter) {
- this.filter = filter;
+ public synchronized boolean getEnabled(final AAAFilter aaaFilter) {
+ this.filter = aaaFilter;
return enabled;
}
}
* Accounter is a common place to output AAA messages. Use this class through
* invoking <code>Logger.output("message")</code>.
*/
-public class Accounter {
+public final class Accounter {
private static final Logger LOG = LoggerFactory.getLogger(Accounter.class);
}
/**
- * Account for a particular <code>message</code>
+ * Account for a particular <code>message</code>.
*
* @param message A message for the aggregated AAA log.
*/
* is that <code>AAAFilter</code> was designed to support the existing noauth
* mechanism, while this filter cannot be disabled.
*
+ * <p>
* This class is also responsible for delivering debug information; to enable these
* debug statements, please issue the following in the karaf shell:
*
}
@Override
- public void onFailure(final AuthenticationToken authenticationToken, final AuthenticationException e) {
+ public void onFailure(final AuthenticationToken authenticationToken,
+ final AuthenticationException authenticationException) {
if (LOG.isDebugEnabled()) {
LOG.debug(AuthenticationTokenUtils.generateUnsuccessfulAuthenticationMessage(authenticationToken));
}
/**
* Utility methods for forming audit trail output based on an <code>AuthenticationToken</code>.
*/
-public class AuthenticationTokenUtils {
+public final class AuthenticationTokenUtils {
/**
- * default value used in messaging when the "user" field is unparsable from the HTTP REST request
+ * default value used in messaging when the "user" field is unparsable from the HTTP REST request.
*/
static final String DEFAULT_USERNAME = "an unknown user";
import org.slf4j.LoggerFactory;
/**
- * MoonOAuthFilter filters oauth1 requests form token based authentication
+ * MoonOAuthFilter filters oauth1 requests form token based authentication.
*
* @author Alioune BA alioune.ba@orange.com
*/
}
@Override
- protected UsernamePasswordToken createToken(final ServletRequest request, final ServletResponse response) throws Exception {
+ protected UsernamePasswordToken createToken(final ServletRequest request,
+ final ServletResponse response) throws Exception {
final HttpServletRequest httpRequest;
final OAuthRequest oauthRequest;
try {
@Override
protected boolean onLoginSuccess(final AuthenticationToken token, final Subject subject,
- final ServletRequest request, final ServletResponse response) throws Exception {
+ final ServletRequest request, final ServletResponse response) throws Exception {
final HttpServletResponse httpResponse;
try {
}
@Override
- protected boolean onLoginFailure(final AuthenticationToken token, final AuthenticationException e,
- final ServletRequest request, final ServletResponse response) {
+ protected boolean onLoginFailure(final AuthenticationToken token,
+ final AuthenticationException authenticationException,
+ final ServletRequest request, final ServletResponse response) {
final HttpServletResponse resp;
try {
}
@Override
+ @SuppressWarnings("checkstyle:IllegalCatch")
protected boolean executeLogin(final ServletRequest request, final ServletResponse response) throws Exception {
final HttpServletRequest req;
if (req.getServletPath().equals(TOKEN_GRANT_ENDPOINT)) {
final UsernamePasswordToken token = createToken(request, response);
if (token == null) {
- final String msg = "A valid non-null AuthenticationToken " +
- "must be created in order to execute a login attempt.";
+ final String msg = "A valid non-null AuthenticationToken "
+ + "must be created in order to execute a login attempt.";
throw new IllegalStateException(msg);
}
try {
error(resp, SC_UNAUTHORIZED, e.getMessage());
} catch (final OAuthProblemException oe) {
error(resp, oe);
- } catch (final Exception e) {
+ } catch (final RuntimeException e) {
error(resp, e);
}
return false;
}
- private void oauthAccessTokenResponse(final HttpServletResponse resp, final Claim claim, final String clientId, final String token)
- throws OAuthSystemException, IOException {
+ private void oauthAccessTokenResponse(final HttpServletResponse resp, final Claim claim, final String clientId,
+ final String token) throws OAuthSystemException, IOException {
if (claim == null) {
throw new AuthenticationException(UNAUTHORIZED);
}
// Cache this token...
- final Authentication auth = new AuthenticationBuilder(new ClaimBuilder(claim).setClientId(
- clientId).build()).setExpiration(tokenExpiration()).build();
+ final Authentication auth = new AuthenticationBuilder(new ClaimBuilder(claim).setClientId(clientId).build())
+ .setExpiration(tokenExpiration()).build();
tokenStore.put(token, auth);
final OAuthResponse r = OAuthASResponse.tokenResponse(SC_CREATED).setAccessToken(token)
- .setTokenType(TokenType.BEARER.toString())
- .setExpiresIn(Long.toString(auth.expiration()))
- .buildJSONMessage();
+ .setTokenType(TokenType.BEARER.toString()).setExpiresIn(Long.toString(auth.expiration()))
+ .buildJSONMessage();
write(resp, r);
}
- private void write(final HttpServletResponse resp, final OAuthResponse r) throws IOException {
- resp.setStatus(r.getResponseStatus());
+ private void write(final HttpServletResponse resp, final OAuthResponse response) throws IOException {
+ resp.setStatus(response.getResponseStatus());
PrintWriter pw = resp.getWriter();
- pw.print(r.getBody());
+ pw.print(response.getBody());
pw.flush();
pw.close();
}
}
/**
- * Utility method used to emit an error OAuthResponse with the given HTTP code
+ * Utility method used to emit an error OAuthResponse with the given HTTP code.
*/
private void error(final HttpServletResponse resp, final int httpCode, final String error) {
try {
- final OAuthResponse r = OAuthResponse.errorResponse(httpCode).setError(error)
- .buildJSONMessage();
+ final OAuthResponse r = OAuthResponse.errorResponse(httpCode).setError(error).buildJSONMessage();
write(resp, r);
} catch (final IOException | OAuthSystemException ex) {
LOG.error("Failed to write the error ", ex);
}
}
- private void error(final HttpServletResponse resp, final OAuthProblemException e) {
+ private void error(final HttpServletResponse resp, final OAuthProblemException oauthProblemException) {
try {
- final OAuthResponse r = OAuthResponse.errorResponse(SC_BAD_REQUEST).error(e)
- .buildJSONMessage();
+ final OAuthResponse r = OAuthResponse.errorResponse(SC_BAD_REQUEST).error(oauthProblemException)
+ .buildJSONMessage();
write(resp, r);
} catch (final IOException | OAuthSystemException ex) {
LOG.error("Failed to write the error ", ex);
}
}
- private void error(final HttpServletResponse resp, final Exception e) {
+ private void error(final HttpServletResponse resp, final Exception exception) {
try {
final OAuthResponse r = OAuthResponse.errorResponse(SC_INTERNAL_SERVER_ERROR)
- .setError(e.getClass().getName())
- .setErrorDescription(e.getMessage()).buildJSONMessage();
+ .setError(exception.getClass().getName()).setErrorDescription(exception.getMessage())
+ .buildJSONMessage();
write(resp, r);
} catch (final IOException | OAuthSystemException ex) {
LOG.error("Failed to write the error ", ex);
}
}
-
}
* Extends <code>BasicHttpAuthenticationFilter</code> to include ability to
* authenticate OAuth2 tokens.
*
+ * <p>
* This behavior is enabled by default for backwards compatibility. To disable
* OAuth2 functionality, just comment out the following line from the
* <code>etc/shiro.ini</code> file:
import org.opendaylight.aaa.api.Claim;
/**
- * MoonPrincipal contains all user's information returned by moon on successful authentication
+ * MoonPrincipal contains all user's information returned by moon on successful authentication.
*
* @author Alioune BA alioune.ba@orange.com
*/
private final ImmutableSet<String> roles;
private final String token;
-
public MoonPrincipal(final String username, final String domain, final String userId,
final Set<String> roles, final String token) {
this.token = token;
}
- public MoonPrincipal createODLPrincipal(final String username, final String domain,
- final String userId, final Set<String> roles, final String token) {
+ public MoonPrincipal createODLPrincipal(final String userName, final String theDomain,
+ final String theUserId, final Set<String> theRoles, final String theToken) {
- return new MoonPrincipal(username, domain, userId, roles,token);
+ return new MoonPrincipal(userName, theDomain, theUserId, theRoles,theToken);
}
- public Claim principalToClaim () {
+ public Claim principalToClaim() {
return new MoonClaim("", this.getUserId(), this.getUsername(), this.getDomain(), this.getRoles());
}
return this.roles;
}
- public String getToken(){
+ public String getToken() {
return this.token;
}
*/
package org.opendaylight.aaa.shiro.moon;
-
import java.io.IOException;
-
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
LOG.info("MoonTokenEndpoint Servlet doPost: {} {}", req.getServletPath(), req.getRequestURI());
}
-
}
* An ODL specific principal which stores some critical information about the user
* making the auth request.
*/
-public class ODLPrincipalImpl implements ODLPrincipal {
+public final class ODLPrincipalImpl implements ODLPrincipal {
private final String username;
private final String domain;
}
@Override
+ @SuppressWarnings("checkstyle:AvoidHidingCauseException")
protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken authenticationToken) {
try {
final boolean hasSslVerification = getSslVerification();
final Optional<HttpAuthorization> authorizationOptional;
try {
authorizationOptional = getHttpAuthzContainer(dataBroker);
- } catch(ExecutionException | InterruptedException e) {
+ } catch (ExecutionException | InterruptedException e) {
// Something went completely wrong trying to read the authz container. Deny access.
LOG.debug("Error accessing the Http Authz Container", e);
return false;
- } catch(final ReadFailedException e) {
+ } catch (final ReadFailedException e) {
// The MDSAL read attempt failed. fail-closed to prevent unauthorized access
LOG.warn("MDSAL attempt to read Http Authz Container failed, disallowing access", e);
return false;
final HttpAuthorization httpAuthorization = authorizationOptional.get();
final Policies policies = httpAuthorization.getPolicies();
- final List<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.http.authorization.policies.Policies> policiesList =
- policies.getPolicies();
- if(policiesList.isEmpty()) {
+ final List<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.http.authorization
+ .policies.Policies>
+ policiesList = policies.getPolicies();
+ if (policiesList.isEmpty()) {
// The authorization container exists, but no rules are present. Allow access.
LOG.debug("Exiting successfully early since no authorization rules exist");
return true;
}
- for (org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.http.authorization.policies.Policies policy :
- policiesList) {
+ for (org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.http.authorization
+ .policies.Policies policy : policiesList) {
final String resource = policy.getResource();
final boolean pathsMatch = pathsMatch(resource, requestURI);
if (pathsMatch) {
final String role = permission.getRole();
LOG.trace("role={}", role);
final List<Permissions.Actions> actions = permission.getActions();
- for(Permissions.Actions action : actions) {
+ for (Permissions.Actions action : actions) {
LOG.trace("action={}", action.getName());
- if(action.getName().equalsIgnoreCase(method)) {
+ if (action.getName().equalsIgnoreCase(method)) {
final boolean hasRole = subject.hasRole(role);
LOG.trace("hasRole({})={}", role, hasRole);
if (hasRole) {
// iterate through and determine the appropriate roles based on the programmed grants
final Grants grants = auth.getGrants();
- final List<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.authentication.grants.Grants> grantsList = grants.getGrants();
- for (Grant grant : grantsList ) {
+ final List<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.authentication
+ .grants.Grants> grantsList = grants.getGrants();
+ for (Grant grant : grantsList) {
if (grant.getUserid().equals(odlPrincipal.getUserId())) {
final Roles roles = auth.getRoles();
if (roles != null) {
- final List<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.authentication.roles.Roles> rolesList =
- roles.getRoles();
- for (org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.authentication.roles.Roles role : rolesList) {
+ final List<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214
+ .authentication.roles.Roles> rolesList = roles.getRoles();
+ for (org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214
+ .authentication.roles.Roles role : rolesList) {
if (role.getRoleid().equals(grant.getRoleid())) {
authRoles.add(role.getRoleid());
}
* @return the <code>authentication</code> container
*/
private Optional<Authentication> getAuthenticationContainer() {
- try (final ReadOnlyTransaction ro = dataBroker.newReadOnlyTransaction()) {
+ try (ReadOnlyTransaction ro = dataBroker.newReadOnlyTransaction()) {
final CheckedFuture<Optional<Authentication>, ReadFailedException> result =
ro.read(LogicalDatastoreType.CONFIGURATION, AUTH_IID);
if (opt.isPresent()) {
final Authentication auth = opt.get();
final Users users = auth.getUsers();
- final List<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.authentication.users.Users> usersList =
- users.getUsers();
- for (org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.authentication.users.Users u : usersList) {
+ final List<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.authentication
+ .users.Users> usersList = users.getUsers();
+ for (org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.authentication.users
+ .Users u : usersList) {
final String inputUsername = HeaderUtils.extractUsername(username);
final String domainId = HeaderUtils.extractDomain(username);
final String inputUserId = String.format("%s@%s", inputUsername, domainId);
final boolean userEnabled = u.isEnabled();
- if(!userEnabled) {
+ if (!userEnabled) {
LOG.trace("userId={} is skipped because it is disabled", u.getUserid());
}
- if(userEnabled && u.getUserid().equals(inputUserId)) {
+ if (userEnabled && u.getUserid().equals(inputUserId)) {
final String inputPassword = TokenUtils.extractPassword(authenticationToken);
final String hashedInputPassword = SHA256Calculator.getSHA256(inputPassword, u.getSalt());
if (hashedInputPassword.equals(u.getPassword())) {
- final ODLPrincipal odlPrincipal = ODLPrincipalImpl.createODLPrincipal(inputUsername,domainId,inputUserId);
+ final ODLPrincipal odlPrincipal = ODLPrincipalImpl
+ .createODLPrincipal(inputUsername, domainId, inputUserId);
return new SimpleAuthenticationInfo(odlPrincipal, inputPassword, getName());
}
}
}
@Override
- protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken authenticationToken) throws AuthenticationException {
+ protected AuthenticationInfo doGetAuthenticationInfo(
+ final AuthenticationToken authenticationToken) throws AuthenticationException {
final String username;
final String password;
final String domain = MOON_DEFAULT_DOMAIN;
password = new String(upt.getPassword());
- final MoonPrincipal moonPrincipal = moonAuthenticate(username,password,domain);
- if (moonPrincipal != null){
- return new SimpleAuthenticationInfo(moonPrincipal, password.toCharArray(),getName());
+ final MoonPrincipal moonPrincipal = moonAuthenticate(username, password, domain);
+ if (moonPrincipal != null) {
+ return new SimpleAuthenticationInfo(moonPrincipal, password.toCharArray(), getName());
} else {
return null;
}
final String url = String.format("http://%s:%s/moon/auth/tokens", server, port);
LOG.debug("Moon server is at: {}:{} and will be accessed through {}", server, port, url);
final WebResource webResource = client.resource(url);
- final String input = "{\"username\": \""+ username + "\"," + "\"password\":" + "\"" + password + "\"," + "\"project\":" + "\"" + domain + "\"" + "}";
+ final String input = "{\"username\": \"" + username + "\"," + "\"password\":" + "\"" + password + "\","
+ + "\"project\":" + "\"" + domain + "\"" + "}";
final ClientResponse response = webResource.type("application/json").post(ClientResponse.class, input);
output = response.getEntity(String.class);
* package, <code>org.opendaylightaaa.shiro.realm</code>, which enables easier
* import by consuming servlets.
*
+ * <p>
* To enable the <code>ODLActiveDirectoryRealm</code>, modify the realms
* declaration in <code>etc/shiro.ini</code> as follows:
* <code>adRealm = ODLActiveDirectoryRealm
* JDBC-supporting data source. This can ease deployment with existing OSS
* systems.
*
+ * <p>
* To enabled the <code>ODLJdbcRealm</code>, modify the realms declaration in
* <code>etc/shiro.ini</code> as follows:
* <code>
* additional Authorization capabilities. To enable this Realm, add the
* following to <code>shiro.ini</code>:
*
- *<code>#ldapRealm = ODLJndiLdapRealmAuthNOnly
- *#ldapRealm.userDnTemplate = uid={0},ou=People,dc=DOMAIN,dc=TLD
- *#ldapRealm.contextFactory.url = ldap://URL:389
- *#ldapRealm.searchBase = dc=DOMAIN,dc=TLD
- *#ldapRealm.ldapAttributeForComparison = objectClass
- *# The CSV list of enabled realms. In order to enable a realm, add it to the
- *# list below:
+ * <p>
+ * <code>#ldapRealm = ODLJndiLdapRealmAuthNOnly
+ * #ldapRealm.userDnTemplate = uid={0},ou=People,dc=DOMAIN,dc=TLD
+ * #ldapRealm.contextFactory.url = ldap://URL:389
+ * #ldapRealm.searchBase = dc=DOMAIN,dc=TLD
+ * #ldapRealm.ldapAttributeForComparison = objectClass
+ * # The CSV list of enabled realms. In order to enable a realm, add it to the
+ * # list below:
* securityManager.realms = $tokenAuthRealm, $ldapRealm</code>
*
+ * <p>
* The values above are specific to the deployed LDAP domain. If the defaults
* are not sufficient, alternatives can be derived through enabling
* <code>TRACE</code> level logging. To enable <code>TRACE</code> level
*
* @see <code>org.apache.shiro.realm.ldap.JndiLdapRealm</code>
* @see <a
- * href="https://shiro.apache.org/static/1.2.3/apidocs/org/apache/shiro/realm/ldap/JndiLdapRealm.html">Shiro
- * documentation</a>
+ * href="https://shiro.apache.org/static/1.2.3/apidocs/org/apache/shiro/realm/ldap/JndiLdapRealm.html">Shiro
+ * documentation</a>
*/
public class ODLJndiLdapRealm extends JndiLdapRealm implements Nameable {
/**
* Strategy to determine how groups are mapped to roles.
*/
- private static final GroupsToRolesMappingStrategy GROUPS_TO_ROLES_MAPPING_STRATEGY =
- new BestAttemptGroupToRolesMappingStrategy();
+ private static final GroupsToRolesMappingStrategy GROUPS_TO_ROLES_MAPPING_STRATEGY
+ = new BestAttemptGroupToRolesMappingStrategy();
/**
* The searchBase for the ldap query, which indicates the LDAP realms to
* .apache.shiro.authc.AuthenticationToken)
*/
@Override
- protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
- throws AuthenticationException {
+ protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// Delegates all AuthN lookup responsibility to the super class
try {
}
/**
- * Logs an incoming LDAP connection
+ * Logs an incoming LDAP connection.
*
- * @param username
- * the requesting user
+ * @param username the requesting user
*/
protected void logIncomingConnection(final String username) {
LOG.info("AAA LDAP connection from {}", username);
}
/**
- * Extracts the username from <code>token</code>
+ * Extracts the username from <code>token</code>.
*
* @param token Encoded token which could contain a username
* @return The extracted username
- * @throws ClassCastException
- * The incoming token is not username/password (i.e., X.509
- * certificate)
+ * @throws ClassCastException The incoming token is not username/password (i.e., X.509
+ * certificate)
*/
public static String getUsername(AuthenticationToken token) throws ClassCastException {
if (null == token) {
return (String) token.getPrincipal();
}
- @Override
- protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
-
- AuthorizationInfo ai = null;
- try {
- ai = this.queryForAuthorizationInfo(principals, getContextFactory());
- } catch (NamingException e) {
- LOG.error("Unable to query for AuthZ info", e);
- }
- return ai;
- }
-
/**
- * extracts a username from <code>principals</code>
+ * extracts a username from <code>principals</code>.
*
* @param principals A single principal extracted for the username
* @return The username if possible
- * @throws ClassCastException
- * the PrincipalCollection contains an element that is not in
- * username/password form (i.e., X.509 certificate)
+ * @throws ClassCastException the PrincipalCollection contains an element that is not in
+ * username/password form (i.e., X.509 certificate)
*/
protected String getUsername(final PrincipalCollection principals) throws ClassCastException {
return (String) getAvailablePrincipal(principals);
}
+ @Override
+ protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
+
+ AuthorizationInfo ai = null;
+ try {
+ ai = this.queryForAuthorizationInfo(principals, getContextFactory());
+ } catch (NamingException e) {
+ LOG.error("Unable to query for AuthZ info", e);
+ }
+ return ai;
+ }
+
/*
* (non-Javadoc)
*
*
* <code>/** = authcBasic, roles[person]</code>
*
- * @see org.apache.shiro.realm.ldap.JndiLdapRealm#queryForAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection, org.apache.shiro.realm.ldap.LdapContextFactory)
+ * @see org.apache.shiro.realm.ldap.JndiLdapRealm#queryForAuthorizationInfo(org.apache.shiro.subject
+ * .PrincipalCollection, org.apache.shiro.realm.ldap.LdapContextFactory)
*/
@Override
protected AuthorizationInfo queryForAuthorizationInfo(PrincipalCollection principals,
- LdapContextFactory ldapContextFactory) throws NamingException {
+ LdapContextFactory ldapContextFactory) throws
+ NamingException {
AuthorizationInfo authorizationInfo = null;
try {
* extracts the Set of roles associated with a user based on the username
* and ldap context (server).
*
- * @param username The username for the request
+ * @param username The username for the request
* @param ldapContext The specific system context provided by <code>shiro.ini</code>
* @return A set of roles
* @throws NamingException If the ldap search fails
*/
- protected Set<String> getRoleNamesForUser(final String username, final LdapContext ldapContext)
- throws NamingException {
+ protected Set<String> getRoleNamesForUser(final String username,
+ final LdapContext ldapContext) throws NamingException {
final Set<String> roleNames = new LinkedHashSet<String>();
final SearchControls searchControls = createSearchControls();
LOG.debug("Asking the configured LDAP about which groups uid=\"{}\" belongs to using "
- + "searchBase=\"{}\" ldapAttributeForComparison=\"{}\"",
- username, searchBase, ldapAttributeForComparison);
- final NamingEnumeration<SearchResult> answer = ldapContext.search(searchBase,
- String.format("%s=%s", UID, username), searchControls);
+ + "searchBase=\"{}\" ldapAttributeForComparison=\"{}\"", username, searchBase,
+ ldapAttributeForComparison);
+ final NamingEnumeration<SearchResult> answer = ldapContext
+ .search(searchBase, String.format("%s=%s", UID, username), searchControls);
while (answer.hasMoreElements()) {
final SearchResult searchResult = answer.next();
LOG.debug("LDAP returned \"{}\" attribute for \"{}\"", attr.getID(), username);
if (attr.getID().equals(ldapAttributeForComparison)) {
final Collection<String> groupNamesExtractedFromLdap = LdapUtils.getAllAttributeValues(attr);
- final Map<String, Set<String>> groupsToRoles = this.GROUPS_TO_ROLES_MAPPING_STRATEGY.mapGroupsToRoles(
- groupNamesExtractedFromLdap, ROLE_NAMES_DELIMITER, groupRolesMap);
+ final Map<String, Set<String>> groupsToRoles = this.GROUPS_TO_ROLES_MAPPING_STRATEGY
+ .mapGroupsToRoles(groupNamesExtractedFromLdap, ROLE_NAMES_DELIMITER, groupRolesMap);
final Collection<String> roleNamesFromLdapGroups;
// map the groups
if (groupRolesMap != null) {
roleNamesFromLdapGroups = new HashSet<>();
- for (String rolesKey : groupsToRoles.keySet()) {
+ for (String rolesKey : groupsToRoles.keySet()) {
roleNamesFromLdapGroups.addAll(groupsToRoles.get(rolesKey));
}
if (LOG.isDebugEnabled()) {
for (String group : groupsToRoles.keySet()) {
LOG.debug("Mapped the \"{}\" LDAP group to \"{}\" ODL role for \"{}\"", group,
- groupsToRoles.get(group), username);
+ groupsToRoles.get(group), username);
}
}
} else {
- LOG.debug("Since groupRolesMap was unspecified, no mapping is attempted so " +
- "the role names are set to the extracted group names");
+ LOG.debug("Since groupRolesMap was unspecified, no mapping is attempted so "
+ + "the role names are set to the extracted group names");
roleNamesFromLdapGroups = groupNamesExtractedFromLdap;
if (LOG.isDebugEnabled()) {
for (String group : groupNamesExtractedFromLdap) {
- LOG.debug("Mapped the \"{}\" LDAP group to \"{}\" ODL role for \"{}\"",
- group, group, username);
+ LOG.debug("Mapped the \"{}\" LDAP group to \"{}\" ODL role for \"{}\"", group,
+ group, username);
}
}
}
}
/**
- * A utility method to help create the search controls for the LDAP lookup
+ * A utility method to help create the search controls for the LDAP lookup.
*
* @return A generic set of search controls for LDAP scoped to subtree
*/
* without worrying about resolving LDAP attributes (groups) to OpenDaylight
* roles.
*
+ * <p>
* The motivation for subclassing Shiro's implementation is two-fold: 1) Enhance
* the default logging of Shiro. This allows us to more easily log incoming
* connections, providing some security auditing. 2) Provide a common package in
}
/**
- * Logs an incoming LDAP connection
+ * Logs an incoming LDAP connection.
*
* @param username
* the requesting user
}
/**
- * Extracts the username from <code>token</code>
+ * Extracts the username from <code>token</code>.
*
* @param token Which possibly contains a username
* @return the username if it can be extracted
public class TokenAuthRealm extends AuthorizingRealm {
/**
- * The unique identifying name for <code>TokenAuthRealm</code>
+ * 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
+ * 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\"}";
+ private static final String AUTHENTICATION_SERVICE_UNAVAILABLE_MESSAGE =
+ "{\"error\":\"Authentication service unavailable\"}";
/**
- * The message that is displayed if credentials are missing or malformed
+ * 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
+ * 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\"}";
+ 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
+ * unable to validate the given credentials.
*/
private static final String UNABLE_TO_AUTHENTICATE = "{\"error\":\"Could not authenticate\"}";
try {
odlPrincipal = (ODLPrincipal) primaryPrincipal;
return new SimpleAuthorizationInfo(odlPrincipal.getRoles());
- } catch(ClassCastException e) {
+ } catch (ClassCastException e) {
LOG.error("Couldn't decode authorization request", e);
}
return new SimpleAuthorizationInfo();
* .apache.shiro.authc.AuthenticationToken)
*/
@Override
- protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
- throws AuthenticationException {
+ protected AuthenticationInfo doGetAuthenticationInfo(
+ AuthenticationToken authenticationToken) throws AuthenticationException {
final String username;
final String password;
LOG.debug("Authentication attempt successful");
authenticationService.set(auth);
final ODLPrincipal odlPrincipal = ODLPrincipalImpl.createODLPrincipal(auth);
- return new SimpleAuthenticationInfo(odlPrincipal, password.toCharArray(),
- getName());
+ return new SimpleAuthenticationInfo(odlPrincipal, password.toCharArray(), getName());
}
} catch (AuthenticationException ae) {
LOG.debug("Authentication attempt unsuccessful");
/**
* Convert LDAP groups to ODL roles.
*
- * @param groups A collection of String groups extracted from making an LDAP query.
- * @param delimeter A separator to allow multiple target roles.
+ * @param groups A collection of String groups extracted from making an LDAP query.
+ * @param delimiter A separator to allow multiple target roles.
* @param groupRolesMap The association between groups to roles
* @return A <code>non-null</code> map with group as the key and roles as the value
*/
- Map<String, Set<String>> mapGroupsToRoles(final Collection<String> groups, final String delimeter,
- final Map<String, String> groupRolesMap);
+ Map<String, Set<String>> mapGroupsToRoles(Collection<String> groups, String delimiter,
+ Map<String, String> groupRolesMap);
}
/**
* Utilities for manipulating <code>AuthenticationToken</code> instances from Shiro.
*/
-public class TokenUtils {
+public final class TokenUtils {
+
+ private TokenUtils() {
+ }
+
/**
- * extract the username from an <code>AuthenticationToken</code>
+ * extract the username from an <code>AuthenticationToken</code>.
*
- * @param authenticationToken
- * @return
- * @throws ClassCastException
- * @throws NullPointerException
+ * @param authenticationToken authentication token
+ * @return string with the user name
*/
public static String extractUsername(final AuthenticationToken authenticationToken)
throws ClassCastException, NullPointerException {
}
/**
- * extract the password from an <code>AuthenticationToken</code>
+ * extract the password from an <code>AuthenticationToken</code>.
*
- * @param authenticationToken
- * @return
- * @throws ClassCastException
- * @throws NullPointerException
+ * @param authenticationToken authentication token
+ * @return string with the extracted password
*/
public static String extractPassword(final AuthenticationToken authenticationToken)
throws ClassCastException, NullPointerException {
* An utility that represents an HTTP client that allows to make
* HTTP requests.
*/
+//Suppressed so UT's can mock it using Mockito.
+@SuppressWarnings("checkstyle:FinalClass")
public class SimpleHttpClient {
private final Client client;
/**
* Sets the SSLContext to be used for SSL requests.
*
- * @param sslContext the SSLContext.
+ * @param context the SSLContext.
* @return self, the client builder.
*/
- public Builder sslContext(final SSLContext sslContext) {
- this.sslContext = sslContext;
+ public Builder sslContext(final SSLContext context) {
+ this.sslContext = context;
return this;
}
/**
* Sets the hostname verifier the request is made with.
*
- * @param hostnameVerifier the hostname verifier.
+ * @param verifier the hostname verifier.
* @return self, the client builder.
*/
- public Builder hostnameVerifier(final HostnameVerifier hostnameVerifier) {
- this.hostnameVerifier = hostnameVerifier;
+ public Builder hostnameVerifier(final HostnameVerifier verifier) {
+ this.hostnameVerifier = verifier;
return this;
}
*
* @param <T> the return type of the request.
*/
+// Suppressed so UT's can mock it using Mockito.
+@SuppressWarnings("checkstyle:FinalClass")
public class SimpleHttpRequest<T> {
private final Client client;
private final Class<T> outputType;
private String method;
private MediaType mediaType;
private Object entity;
- private Map<String, String> queryParams = new HashMap<>();
+ private final Map<String, String> queryParams = new HashMap<>();
private SimpleHttpRequest(final Client client, final Class<T> outputType) {
this.client = client;
}
public static class Builder<T> {
- private SimpleHttpRequest<T> request;
+ private final SimpleHttpRequest<T> request;
Builder(Client client, Class<T> outputType) {
request = new SimpleHttpRequest<>(client, outputType);
* Container for an SSL context that allows untrusted access and a hostname
* verifier that accepts any hostname.
*/
-public class UntrustedSSL {
+public final class UntrustedSSL {
private UntrustedSSL() {}
- private static class InsecureHostnameVerifier {
+ private static final class InsecureHostnameVerifier {
private static final HostnameVerifier INSTANCE = (hostname, session) -> true;
private InsecureHostnameVerifier() {}
}
- private static class InsecureTrustManager {
+ private static final class InsecureTrustManager {
private static final TrustManager[] INSTANCE = new TrustManager[] {
new X509TrustManager() {
private final X509Certificate[] empty = new X509Certificate[] {};
private InsecureTrustManager() {}
}
- private static class InsecureSSLContext {
+ private static final class InsecureSSLContext {
private static final SSLContext INSTANCE = buildSSLContext();
private InsecureSSLContext() {}
/**
* Utilities for HTTP header manipulation.
*/
-public class HeaderUtils {
+public final class HeaderUtils {
public static final String USERNAME_DOMAIN_SEPARATOR = "@";
+ private HeaderUtils() {
+ }
+
/**
+ * Returns a string containing the encoded token.
*
- * @param credentialToken
+ * @param credentialToken token to encode
* @return Base64 encoded token
*/
public static String getEncodedToken(final String credentialToken) {
*
* @param username The request username
* @param password The request password
- * @param domain The request domain
+ * @param domain The request domain
* @return <code>username:password:domain</code>
*/
public static String getUsernamePasswordDomainString(final String username, final String password,
final String domain) {
- return username + HttpBasicAuth.AUTH_SEP + password + HttpBasicAuth.AUTH_SEP + domain;
+ return username + HttpBasicAuth.AUTH_SEP + password + HttpBasicAuth.AUTH_SEP + domain;
}
/**
+ * Returns a string with the authorization header.
*
- * @param encodedToken
+ * @param encodedToken encoded token
* @return Basic <code>encodedToken</code>
*/
public static String getTokenAuthHeader(final String encodedToken) {
}
/**
+ * Returns a map with all the list of headers for the given token.
*
- * @param tokenAuthHeader
+ * @param tokenAuthHeader token authorization header
* @return a map with the basic auth header
*/
public static Map<String, List<String>> formHeadersWithToken(final String tokenAuthHeader) {
- final Map<String, List<String>> headers = new HashMap<String, List<String>>();
- final List<String> headerValue = new ArrayList<String>();
+ final Map<String, List<String>> headers = new HashMap<>();
+ final List<String> headerValue = new ArrayList<>();
headerValue.add(tokenAuthHeader);
headers.put(HttpBasicAuth.AUTH_HEADER, headerValue);
return headers;
*
* @param username Username from the request
* @param password Password from the request
- * @param domain Domain from the request
+ * @param domain Domain from the request
* @return input map for <code>TokenAuth.validate()</code>
*/
public static Map<String, List<String>> formHeaders(final String username, final String password,
}
/**
- * Extract username from the form <code>user</code> or <code>user@domain</code>
+ * Extract username from the form <code>user</code> or <code>user@domain</code>.
*
* @param possiblyQualifiedUsername <code>user</code> or <code>user@domain</code>
* @return username
*/
public static String extractUsername(final String possiblyQualifiedUsername) {
if (possiblyQualifiedUsername.contains(USERNAME_DOMAIN_SEPARATOR)) {
- final String [] qualifiedUserArray = possiblyQualifiedUsername.split(USERNAME_DOMAIN_SEPARATOR);
+ final String[] qualifiedUserArray = possiblyQualifiedUsername.split(USERNAME_DOMAIN_SEPARATOR);
return qualifiedUserArray[0];
}
return possiblyQualifiedUsername;
}
/**
- * Extract domain from the form <code>user</code> or <code>user@domain</code>
+ * Extract domain from the form <code>user</code> or <code>user@domain</code>.
*
* @param possiblyQualifiedUsername <code>user</code> or <code>user@domain</code>
* @return the domain or <code>HttpBasicAuth.DEFAULT_DOMAIN</code>
*/
public static String extractDomain(final String possiblyQualifiedUsername) {
if (possiblyQualifiedUsername.contains(USERNAME_DOMAIN_SEPARATOR)) {
- final String [] qualifiedUserArray = possiblyQualifiedUsername.split(USERNAME_DOMAIN_SEPARATOR);
+ final String[] qualifiedUserArray = possiblyQualifiedUsername.split(USERNAME_DOMAIN_SEPARATOR);
return qualifiedUserArray[1];
}
return HttpBasicAuth.DEFAULT_DOMAIN;
*/
package org.opendaylight.aaa.shiro.tokenauthrealm.auth;
-import static org.opendaylight.aaa.shiro.tokenauthrealm.util.EqualUtil.areEqual;
-import static org.opendaylight.aaa.shiro.tokenauthrealm.util.HashCodeUtil.hash;
-
import java.io.Serializable;
import java.util.Set;
import org.opendaylight.aaa.api.Authentication;
import org.opendaylight.aaa.api.Claim;
-import org.opendaylight.aaa.shiro.tokenauthrealm.util.HashCodeUtil;
import org.opendaylight.aaa.shiro.tokenauthrealm.util.EqualUtil;
+import org.opendaylight.aaa.shiro.tokenauthrealm.util.HashCodeUtil;
/**
* A builder for the authentication context.
return false;
}
Authentication authentication = (Authentication) object;
- return EqualUtil.areEqual(expiration, authentication.expiration()) && EqualUtil.areEqual(claim.roles(), authentication.roles())
- && EqualUtil.areEqual(claim.domain(), authentication.domain())
- && EqualUtil.areEqual(claim.userId(), authentication.userId())
- && EqualUtil.areEqual(claim.user(), authentication.user())
- && EqualUtil.areEqual(claim.clientId(), authentication.clientId());
+ return EqualUtil.areEqual(expiration, authentication.expiration()) && EqualUtil
+ .areEqual(claim.roles(), authentication.roles()) && EqualUtil
+ .areEqual(claim.domain(), authentication.domain()) && EqualUtil
+ .areEqual(claim.userId(), authentication.userId()) && EqualUtil
+ .areEqual(claim.user(), authentication.user()) && EqualUtil
+ .areEqual(claim.clientId(), authentication.clientId());
}
@Override
return this;
}
- public ClaimBuilder addRoles(Set<String> roles) {
- for (String role : roles) {
+ public ClaimBuilder addRoles(Set<String> theRoles) {
+ for (String role : theRoles) {
addRole(role);
}
return this;
final String message = "Login Attempt in Bad Format."
+ " Please provide user:password in Base64 format.";
LOG.info(message);
- throw new AuthenticationException(message);
+ throw new AuthenticationException(message, e);
}
}
}
*/
package org.opendaylight.aaa.shiro.tokenauthrealm.auth;
-import static org.opendaylight.aaa.shiro.tokenauthrealm.util.EqualUtil.areEqual;
-import static org.opendaylight.aaa.shiro.tokenauthrealm.util.HashCodeUtil.hash;
-
import org.opendaylight.aaa.api.PasswordCredentials;
-import org.opendaylight.aaa.shiro.tokenauthrealm.util.HashCodeUtil;
import org.opendaylight.aaa.shiro.tokenauthrealm.util.EqualUtil;
+import org.opendaylight.aaa.shiro.tokenauthrealm.util.HashCodeUtil;
/**
* {@link PasswordCredentials} builder.
import static org.junit.Assert.assertTrue;
import org.junit.Test;
-import org.opendaylight.aaa.shiro.ServiceProxy;
import org.opendaylight.aaa.shiro.filters.AAAFilter;
public class ServiceProxyTest {
public class TestAppender extends AppenderBase<LoggingEvent> {
/**
- * stores all log events in memory, instead of file
+ * stores all log events in memory, instead of file.
*/
private List<LoggingEvent> events = new Vector<>();
private static volatile TestAppender currentInstance;
/**
- * keeps track of the current instance
+ * keeps track of the current instance.
*/
public TestAppender() {
currentInstance = this;
}
@Override
- protected void append(final LoggingEvent e) {
- events.add(e);
+ protected void append(final LoggingEvent loggingEvent) {
+ events.add(loggingEvent);
}
/**
package org.opendaylight.aaa.shiro.filters;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
import ch.qos.logback.classic.spi.LoggingEvent;
import java.util.List;
-
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
package org.opendaylight.aaa.shiro.filters;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
/**
* Tests the Dynamic Authorization Filter.
*/
+@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
public class MDSALDynamicAuthorizationFilterTest {
@Before
}
// test helper method to generate some cool mdsal data
- private DataBroker getTestData(final String resource, final String role,
- final String description, final Permissions.Actions actions) throws Exception {
+ private DataBroker getTestData(final String resource, final String role, final String description,
+ final Permissions.Actions actions) throws Exception {
final List<Permissions.Actions> actionsList = Lists.newArrayList(actions);
final Permissions permissions = mock(Permissions.class);
when(permissions.getRole()).thenReturn(role);
when(permissions.getActions()).thenReturn(actionsList);
final List<Permissions> permissionsList = Lists.newArrayList(permissions);
- final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.http.authorization.policies.Policies innerPolicies =
- mock(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.http.authorization.policies.Policies.class);
+ final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.http.authorization
+ .policies.Policies
+ innerPolicies = mock(
+ org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.http.authorization
+ .policies.Policies.class);
when(innerPolicies.getResource()).thenReturn(resource);
when(innerPolicies.getDescription()).thenReturn(description);
when(innerPolicies.getPermissions()).thenReturn(permissionsList);
- final List<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.http.authorization.policies.Policies> policiesList =
- Lists.newArrayList(innerPolicies);
+ final List<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.http.authorization
+ .policies.Policies>
+ policiesList = Lists.newArrayList(innerPolicies);
final Policies policies = mock(Policies.class);
when(policies.getPolicies()).thenReturn(policiesList);
final HttpAuthorization httpAuthorization = mock(HttpAuthorization.class);
//
// Ensure that data can be extracted appropriately.
final DataBroker dataBroker = getTestData();
- final Optional<HttpAuthorization> httpAuthorizationOptional =
- MDSALDynamicAuthorizationFilter.getHttpAuthzContainer(dataBroker);
+ final Optional<HttpAuthorization> httpAuthorizationOptional = MDSALDynamicAuthorizationFilter
+ .getHttpAuthzContainer(dataBroker);
assertNotNull(httpAuthorizationOptional);
final HttpAuthorization authz = httpAuthorizationOptional.get();
final Optional<DataObject> dataObjectOptional = mock(Optional.class);
when(dataObjectOptional.isPresent()).thenReturn(false);
- final CheckedFuture<Optional<DataObject>, ReadFailedException> cf =
- Futures.immediateFailedCheckedFuture(new ReadFailedException("Test Fail"));
+ final CheckedFuture<Optional<DataObject>, ReadFailedException> cf = Futures
+ .immediateFailedCheckedFuture(new ReadFailedException("Test Fail"));
final ReadOnlyTransaction rot = mock(ReadOnlyTransaction.class);
when(rot.read(any(), any())).thenReturn(cf);
final DataBroker dataBroker = mock(DataBroker.class);
//
// Create some mock data which has a couple of rules which may/may not match. This
// test ensures the correct application of said rules.
- final List<Permissions.Actions> actionsList = Lists.newArrayList(Permissions.Actions.Get,
- Permissions.Actions.Delete, Permissions.Actions.Patch, Permissions.Actions.Put,
- Permissions.Actions.Post);
+ final List<Permissions.Actions> actionsList = Lists
+ .newArrayList(Permissions.Actions.Get, Permissions.Actions.Delete, Permissions.Actions.Patch,
+ Permissions.Actions.Put, Permissions.Actions.Post);
final String role = "admin";
final String resource = "/**";
final String resource2 = "/specialendpoint/**";
when(permissions.getRole()).thenReturn(role);
when(permissions.getActions()).thenReturn(actionsList);
final List<Permissions> permissionsList = Lists.newArrayList(permissions);
- final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.http.authorization.policies.Policies innerPolicies =
- mock(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.http.authorization.policies.Policies.class);
+ final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.http.authorization
+ .policies.Policies
+ innerPolicies = mock(
+ org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.http.authorization
+ .policies.Policies.class);
when(innerPolicies.getResource()).thenReturn(resource);
when(innerPolicies.getDescription()).thenReturn(description);
when(innerPolicies.getPermissions()).thenReturn(permissionsList);
- final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.http.authorization.policies.Policies innerPolicies2 =
- mock(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.http.authorization.policies.Policies.class);
+ final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.http.authorization
+ .policies.Policies
+ innerPolicies2 = mock(
+ org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.http.authorization
+ .policies.Policies.class);
when(innerPolicies2.getResource()).thenReturn(resource2);
final Permissions permissions2 = mock(Permissions.class);
when(permissions2.getRole()).thenReturn("dog");
when(permissions2.getActions()).thenReturn(actionsList);
when(innerPolicies2.getPermissions()).thenReturn(Lists.newArrayList(permissions2));
when(innerPolicies2.getDescription()).thenReturn("Specialized Rule");
- List<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.http.authorization.policies.Policies> policiesList =
- Lists.newArrayList(innerPolicies, innerPolicies2);
+ List<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.http.authorization
+ .policies.Policies>
+ policiesList = Lists.newArrayList(innerPolicies, innerPolicies2);
final Policies policies = mock(Policies.class);
when(policies.getPolicies()).thenReturn(policiesList);
final HttpAuthorization httpAuthorization = mock(HttpAuthorization.class);
final String role = "admin";
final String resource = "/**";
final String description = "Test description";
- final List<Permissions.Actions> actionsList = Lists.newArrayList(
- Permissions.Actions.Get, Permissions.Actions.Put, Permissions.Actions.Delete,
- Permissions.Actions.Patch, Permissions.Actions.Post
- );
+ final List<Permissions.Actions> actionsList = Lists
+ .newArrayList(Permissions.Actions.Get, Permissions.Actions.Put, Permissions.Actions.Delete,
+ Permissions.Actions.Patch, Permissions.Actions.Post);
final Permissions permissions = mock(Permissions.class);
when(permissions.getRole()).thenReturn(role);
when(permissions.getActions()).thenReturn(actionsList);
when(permissions2.getRole()).thenReturn("user");
when(permissions2.getActions()).thenReturn(Lists.newArrayList(Permissions.Actions.Get));
final List<Permissions> permissionsList = Lists.newArrayList(permissions, permissions2);
- final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.http.authorization.policies.Policies innerPolicies =
- mock(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.http.authorization.policies.Policies.class);
+ final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.http.authorization
+ .policies.Policies
+ innerPolicies = mock(
+ org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.http.authorization
+ .policies.Policies.class);
when(innerPolicies.getResource()).thenReturn(resource);
when(innerPolicies.getDescription()).thenReturn(description);
when(innerPolicies.getPermissions()).thenReturn(permissionsList);
- final List<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.http.authorization.policies.Policies> policiesList =
- Lists.newArrayList(innerPolicies);
+ final List<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.http.authorization
+ .policies.Policies>
+ policiesList = Lists.newArrayList(innerPolicies);
final Policies policies = mock(Policies.class);
when(policies.getPolicies()).thenReturn(policiesList);
final HttpAuthorization httpAuthorization = mock(HttpAuthorization.class);
public class ODLJndiLdapRealmTest {
/**
- * throw-away anonymous test class
+ * throw-away anonymous test class.
*/
class TestNamingEnumeration implements NamingEnumeration<SearchResult> {
- /**
- * state variable
- */
+ // State variable
boolean first = true;
/**
"objectClass", "engineering"));
/**
- * returns true the first time, then false for subsequent calls
+ * returns true the first time, then false for subsequent calls.
*/
@Override
public boolean hasMoreElements() {
}
/**
- * returns <code>searchResult</code> then null for subsequent calls
+ * returns <code>searchResult</code> then null for subsequent calls.
*/
@Override
public SearchResult nextElement() {
}
/**
- * does nothing because close() doesn't require any special behavior
+ * does nothing because close() doesn't require any special behavior.
*/
@Override
public void close() throws NamingException {
}
/**
- * returns true the first time, then false for subsequent calls
+ * returns true the first time, then false for subsequent calls.
*/
@Override
public boolean hasMore() throws NamingException {
}
/**
- * returns <code>searchResult</code> then null for subsequent calls
+ * returns <code>searchResult</code> then null for subsequent calls.
*/
@Override
public SearchResult next() throws NamingException {
}
return null;
}
- };
+ }
/**
- * throw away test class
+ * throw away test class.
*
* @author ryan
*/
class TestPrincipalCollection implements PrincipalCollection {
- /**
- *
- */
private static final long serialVersionUID = -1236759619455574475L;
Vector<String> collection = new Vector<String>();
- public TestPrincipalCollection(String element) {
+ TestPrincipalCollection(String element) {
collection.add(element);
}
// TODO Auto-generated method stub
return null;
}
- };
+ }
@Test
public void testGetUsernameAuthenticationToken() {
final String password = "password";
final String domain = "domain";
final String expectedUsernamePasswordString = "user:password:domain";
- assertEquals(expectedUsernamePasswordString, HeaderUtils.getUsernamePasswordDomainString(username, password, domain));
+ assertEquals(expectedUsernamePasswordString, HeaderUtils.getUsernamePasswordDomainString(
+ username, password, domain));
}
@Test
@Test
public void testGetTokenAuthHeader() {
- final String encodedCredentials = HeaderUtils.getEncodedToken(HeaderUtils.getUsernamePasswordDomainString("user1",
- "password", "sdn"));
+ final String encodedCredentials = HeaderUtils.getEncodedToken(HeaderUtils.getUsernamePasswordDomainString(
+ "user1", "password", "sdn"));
final String expectedTokenAuthHeader = "Basic " + encodedCredentials;
assertEquals(expectedTokenAuthHeader, HeaderUtils.getTokenAuthHeader(encodedCredentials));
}
package org.opendaylight.aaa.shiro.realm.mapping.impl;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
-import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import com.sun.jersey.api.client.Client;