Search in sources :

Example 96 with Principal

use of java.security.Principal in project opennms by OpenNMS.

the class OpenNMSJaasAuthenticationBroker method authenticateBasedOnRemoteAddress.

private void authenticateBasedOnRemoteAddress(ConnectionContext context, ConnectionInfo info) {
    boolean grant = false;
    final String connectionString = context.getConnection().getRemoteAddress();
    if (connectionString.startsWith("vm://")) {
        // Always grant VM connections
        grant = true;
    } else {
        final InetAddress remoteAddress = getAddressFromConnectionString(connectionString);
        if (remoteAddress == null) {
            LOG.warn("Unable to determine remote address from connection string: {}", connectionString);
        } else if (trustedHosts.contains(remoteAddress)) {
            grant = true;
        }
    }
    if (!grant) {
        LOG.info("Connection from '{}' is NOT trusted.", connectionString);
        return;
    } else {
        LOG.info("Connection from '{}' is trusted.", connectionString);
        // Always create a new security context, even if it contains the same attributes
        // as the last context
        final SecurityContext securityContext = new SecurityContext(usernameForTrustedHosts) {

            @Override
            public Set<Principal> getPrincipals() {
                return principalsForTrustedHosts;
            }
        };
        context.setSecurityContext(securityContext);
        securityContexts.add(securityContext);
    }
}
Also used : SecurityContext(org.apache.activemq.security.SecurityContext) InetAddress(java.net.InetAddress) Principal(java.security.Principal)

Example 97 with Principal

use of java.security.Principal in project opennms by OpenNMS.

the class LoginModuleUtils method doLogin.

public static boolean doLogin(final OpenNMSLoginHandler handler, final Subject subject, final Map<String, ?> sharedState, final Map<String, ?> options) throws LoginException {
    LOG.debug("OpenNMSLoginModule: login(): handler={}, subject={}, sharedState={}, options={}", handler.getClass(), subject.getClass(), sharedState, options);
    final Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("Username: ");
    callbacks[1] = new PasswordCallback("Password: ", false);
    try {
        handler.callbackHandler().handle(callbacks);
    } catch (final IOException ioe) {
        LOG.debug("IO exception while attempting to prompt for username and password.", ioe);
        throw new LoginException(ioe.getMessage());
    } catch (final UnsupportedCallbackException uce) {
        LOG.debug("Username or password prompt not supported.", uce);
        throw new LoginException(uce.getMessage() + " not available to obtain information from user.");
    }
    final String user = ((NameCallback) callbacks[0]).getName();
    handler.setUser(user);
    if (user == null) {
        final String msg = "Username can not be null.";
        LOG.debug(msg);
        throw new LoginException(msg);
    }
    // password callback get value
    if (((PasswordCallback) callbacks[1]).getPassword() == null) {
        final String msg = "Password can not be null.";
        LOG.debug(msg);
        throw new LoginException(msg);
    }
    final String password = new String(((PasswordCallback) callbacks[1]).getPassword());
    final User configUser;
    final SpringSecurityUser onmsUser;
    try {
        configUser = handler.userConfig().getUser(user);
        onmsUser = handler.springSecurityUserDao().getByUsername(user);
    } catch (final Exception e) {
        final String message = "Failed to retrieve user " + user + " from OpenNMS UserConfig.";
        LOG.debug(message, e);
        throw new LoginException(message);
    }
    if (configUser == null) {
        final String msg = "User  " + user + " does not exist.";
        LOG.debug(msg);
        throw new FailedLoginException(msg);
    }
    if (!handler.userConfig().comparePasswords(user, password)) {
        final String msg = "Login failed: passwords did not match.";
        LOG.debug(msg);
        throw new FailedLoginException(msg);
    }
    ;
    boolean allowed = true;
    final Set<Principal> principals = LoginModuleUtils.createPrincipals(handler, onmsUser.getAuthorities());
    handler.setPrincipals(principals);
    if (handler.requiresAdminRole()) {
        allowed = false;
        for (final Principal principal : principals) {
            final String name = principal.getName().toLowerCase().replaceAll("^role_", "");
            if ("admin".equals(name)) {
                allowed = true;
            }
        }
    }
    if (!allowed) {
        final String msg = "User " + user + " is not an administrator!  OSGi console access is forbidden.";
        LOG.debug(msg);
        throw new LoginException(msg);
    }
    LOG.debug("Successfully logged in {}.", user);
    return true;
}
Also used : User(org.opennms.netmgt.config.users.User) IOException(java.io.IOException) LoginException(javax.security.auth.login.LoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) IOException(java.io.IOException) FailedLoginException(javax.security.auth.login.FailedLoginException) PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) FailedLoginException(javax.security.auth.login.FailedLoginException) PasswordCallback(javax.security.auth.callback.PasswordCallback) LoginException(javax.security.auth.login.LoginException) FailedLoginException(javax.security.auth.login.FailedLoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) Principal(java.security.Principal)

Example 98 with Principal

use of java.security.Principal in project OpenAM by OpenRock.

the class JaspiAuthModuleWrapperTest method setUp.

@BeforeMethod
public void setUp() {
    amLoginModuleBinder = mock(AMLoginModuleBinder.class);
    serverAuthModule = mock(ServerAuthModule.class);
    jaspiAuthModuleWrapper = new JaspiAuthModuleWrapper<ServerAuthModule>(serverAuthModule, "amAuthPersistentCookie") {

        @Override
        protected Map<String, Object> initialize(Subject subject, Map sharedState, Map options) {
            return config;
        }

        @Override
        protected boolean process(MessageInfo messageInfo, Subject clientSubject, Callback[] callbacks) throws LoginException {
            processMethodCalled = true;
            return true;
        }

        @Override
        protected Map<String, Object> initialize(Map requestParamsMap, HttpServletRequest request, HttpServletResponse response, SSOToken ssoToken) throws AuthenticationException {
            return config;
        }

        @Override
        protected void onLoginSuccess(MessageInfo messageInfo, Map requestParamsMap, HttpServletRequest request, HttpServletResponse response, SSOToken ssoToken) throws AuthenticationException {
            onLoginSuccessMethodCalled = true;
        }

        @Override
        public Principal getPrincipal() {
            return null;
        }
    };
    jaspiAuthModuleWrapper.setAMLoginModule(amLoginModuleBinder);
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    given(amLoginModuleBinder.getHttpServletRequest()).willReturn(request);
    given(amLoginModuleBinder.getHttpServletResponse()).willReturn(response);
}
Also used : SSOToken(com.iplanet.sso.SSOToken) AuthenticationException(com.sun.identity.authentication.spi.AuthenticationException) ServerAuthModule(javax.security.auth.message.module.ServerAuthModule) HttpServletResponse(javax.servlet.http.HttpServletResponse) Subject(javax.security.auth.Subject) MessageInfo(javax.security.auth.message.MessageInfo) HttpServletRequest(javax.servlet.http.HttpServletRequest) Callback(javax.security.auth.callback.Callback) LoginException(javax.security.auth.login.LoginException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) HashMap(java.util.HashMap) Map(java.util.Map) Principal(java.security.Principal) BeforeMethod(org.testng.annotations.BeforeMethod)

Example 99 with Principal

use of java.security.Principal in project OpenAM by OpenRock.

the class SessionResourceTest method actionInstanceShouldValidateSessionAndReturnTrueWhenSSOTokenValid.

@Test
public void actionInstanceShouldValidateSessionAndReturnTrueWhenSSOTokenValid() throws SSOException {
    //Given
    final Context context = mock(Context.class);
    final String resourceId = "SSO_TOKEN_ID";
    final ActionRequest request = mock(ActionRequest.class);
    final SSOToken ssoToken = mock(SSOToken.class);
    final Principal principal = mock(Principal.class);
    given(request.getAction()).willReturn(VALIDATE_ACTION_ID);
    given(ssoTokenManager.createSSOToken("SSO_TOKEN_ID")).willReturn(ssoToken);
    given(ssoTokenManager.isValidToken(ssoToken)).willReturn(true);
    given(ssoToken.getPrincipal()).willReturn(principal);
    given(principal.getName()).willReturn("PRINCIPAL");
    //When
    Promise<ActionResponse, ResourceException> promise = sessionResource.actionInstance(context, resourceId, request);
    //Then
    assertThat(promise).succeeded().withContent().booleanAt("valid").isTrue();
    assertThat(promise).succeeded().withContent().stringAt("uid").isEqualTo("demo");
    assertThat(promise).succeeded().withContent().stringAt("realm").isEqualTo("/");
}
Also used : RootContext(org.forgerock.services.context.RootContext) ClientContext(org.forgerock.services.context.ClientContext) RealmContext(org.forgerock.openam.rest.RealmContext) SessionContext(org.forgerock.http.session.SessionContext) SSOTokenContext(org.forgerock.openam.rest.resource.SSOTokenContext) AttributesContext(org.forgerock.services.context.AttributesContext) SecurityContext(org.forgerock.services.context.SecurityContext) Context(org.forgerock.services.context.Context) SSOToken(com.iplanet.sso.SSOToken) Principal(java.security.Principal) Test(org.testng.annotations.Test)

Example 100 with Principal

use of java.security.Principal in project OpenAM by OpenRock.

the class Organization method addChild.

/**
     * Adds a new object to the organization.
     * 
     * @param object
     *            object to be added to the organization
     * @exception AccessRightsException
     *                if an access rights exception occurs
     * @exception EntryAlreadyExistsException
     *                if the entry already exists
     * @exception UMSException
     *                Fail to add the object
     * @supported.api
     */
public void addChild(PersistentObject object) throws AccessRightsException, EntryAlreadyExistsException, UMSException {
    Principal principal = getPrincipal();
    if (principal == null) {
        String msg = i18n.getString(IUMSConstants.BAD_PRINCIPAL_HDL);
        throw new IllegalArgumentException(msg);
    } else if (object == null) {
        String msg = i18n.getString(IUMSConstants.BAD_OBJ_TO_ADD);
        throw new IllegalArgumentException(msg);
    }
    if (object instanceof User) {
        String pcId = getPeopleContainer((User) object);
        if (pcId != null) {
            PeopleContainer pc = new PeopleContainer(getPrincipal(), new Guid(pcId));
            pc.addUser((User) object);
        } else {
            // no match and no default value found
            // For now, the user will be addedd to the organization.
            // May want to add to the default people
            // container(ou=People) instead.
            super.addChild(object);
        }
    } else {
        super.addChild(object);
    }
}
Also used : Principal(java.security.Principal)

Aggregations

Principal (java.security.Principal)931 Test (org.junit.Test)243 Subject (javax.security.auth.Subject)114 EveryonePrincipal (org.apache.jackrabbit.oak.spi.security.principal.EveryonePrincipal)114 HashSet (java.util.HashSet)89 User (org.apache.jackrabbit.api.security.user.User)75 Group (org.apache.jackrabbit.api.security.user.Group)74 Authorizable (org.apache.jackrabbit.api.security.user.Authorizable)58 Privilege (javax.jcr.security.Privilege)57 RepositoryException (javax.jcr.RepositoryException)51 IOException (java.io.IOException)50 ArrayList (java.util.ArrayList)48 HttpServletRequest (javax.servlet.http.HttpServletRequest)47 TestPrincipal (org.apache.jackrabbit.core.security.TestPrincipal)45 AbstractSecurityTest (org.apache.jackrabbit.oak.AbstractSecurityTest)43 EveryonePrincipal (org.apache.jackrabbit.core.security.principal.EveryonePrincipal)42 PrincipalIterator (org.apache.jackrabbit.api.security.principal.PrincipalIterator)40 HashMap (java.util.HashMap)39 PrincipalImpl (org.apache.jackrabbit.oak.spi.security.principal.PrincipalImpl)39 X500Principal (javax.security.auth.x500.X500Principal)38