Search in sources :

Example 66 with Subject

use of javax.security.auth.Subject in project spring-security by spring-projects.

the class JaasApiIntegrationFilterTests method onBeforeTests.

// ~ Methods
// ========================================================================================================
@Before
public void onBeforeTests() throws Exception {
    this.filter = new JaasApiIntegrationFilter();
    this.request = new MockHttpServletRequest();
    this.response = new MockHttpServletResponse();
    authenticatedSubject = new Subject();
    authenticatedSubject.getPrincipals().add(new Principal() {

        public String getName() {
            return "principal";
        }
    });
    authenticatedSubject.getPrivateCredentials().add("password");
    authenticatedSubject.getPublicCredentials().add("username");
    callbackHandler = new CallbackHandler() {

        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (Callback callback : callbacks) {
                if (callback instanceof NameCallback) {
                    ((NameCallback) callback).setName("user");
                } else if (callback instanceof PasswordCallback) {
                    ((PasswordCallback) callback).setPassword("password".toCharArray());
                } else if (callback instanceof TextInputCallback) {
                // ignore
                } else {
                    throw new UnsupportedCallbackException(callback, "Unrecognized Callback " + callback);
                }
            }
        }
    };
    testConfiguration = new Configuration() {

        public void refresh() {
        }

        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            return new AppConfigurationEntry[] { new AppConfigurationEntry(TestLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, new HashMap<String, String>()) };
        }
    };
    LoginContext ctx = new LoginContext("SubjectDoAsFilterTest", authenticatedSubject, callbackHandler, testConfiguration);
    ctx.login();
    token = new JaasAuthenticationToken("username", "password", AuthorityUtils.createAuthorityList("ROLE_ADMIN"), ctx);
    // just in case someone forgot to clear the context
    SecurityContextHolder.clearContext();
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) Configuration(javax.security.auth.login.Configuration) HashMap(java.util.HashMap) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) IOException(java.io.IOException) Subject(javax.security.auth.Subject) TextInputCallback(javax.security.auth.callback.TextInputCallback) AppConfigurationEntry(javax.security.auth.login.AppConfigurationEntry) TextInputCallback(javax.security.auth.callback.TextInputCallback) PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) LoginContext(javax.security.auth.login.LoginContext) JaasAuthenticationToken(org.springframework.security.authentication.jaas.JaasAuthenticationToken) PasswordCallback(javax.security.auth.callback.PasswordCallback) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Principal(java.security.Principal) Before(org.junit.Before)

Example 67 with Subject

use of javax.security.auth.Subject in project spring-security by spring-projects.

the class JaasApiIntegrationFilter method doFilter.

// ~ Methods
// ========================================================================================================
/**
	 * <p>
	 * Attempts to obtain and run as a JAAS <code>Subject</code> using
	 * {@link #obtainSubject(ServletRequest)}.
	 * </p>
	 *
	 * <p>
	 * If the <code>Subject</code> is <code>null</code> and <tt>createEmptySubject</tt> is
	 * <code>true</code>, an empty, writeable <code>Subject</code> is used. This allows
	 * for the <code>Subject</code> to be populated at the time of login. If the
	 * <code>Subject</code> is <code>null</code>, the <code>FilterChain</code> continues
	 * with no additional processing. If the <code>Subject</code> is not <code>null</code>
	 * , the <code>FilterChain</code> is ran with
	 * {@link Subject#doAs(Subject, PrivilegedExceptionAction)} in conjunction with the
	 * <code>Subject</code> obtained.
	 * </p>
	 */
public final void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws ServletException, IOException {
    Subject subject = obtainSubject(request);
    if (subject == null && createEmptySubject) {
        if (logger.isDebugEnabled()) {
            logger.debug("Subject returned was null and createEmtpySubject is true; creating new empty subject to run as.");
        }
        subject = new Subject();
    }
    if (subject == null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Subject is null continue running with no Subject.");
        }
        chain.doFilter(request, response);
        return;
    }
    final PrivilegedExceptionAction<Object> continueChain = new PrivilegedExceptionAction<Object>() {

        public Object run() throws IOException, ServletException {
            chain.doFilter(request, response);
            return null;
        }
    };
    if (logger.isDebugEnabled()) {
        logger.debug("Running as Subject " + subject);
    }
    try {
        Subject.doAs(subject, continueChain);
    } catch (PrivilegedActionException e) {
        throw new ServletException(e.getMessage(), e);
    }
}
Also used : ServletException(javax.servlet.ServletException) PrivilegedActionException(java.security.PrivilegedActionException) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) Subject(javax.security.auth.Subject)

Example 68 with Subject

use of javax.security.auth.Subject in project blade by biezhi.

the class PropertyUserStore method loadUsers.

/* ------------------------------------------------------------ */
protected void loadUsers() throws IOException {
    if (_configPath == null)
        return;
    if (LOG.isDebugEnabled()) {
        LOG.debug("Loading " + this + " from " + _configPath);
    }
    Properties properties = new Properties();
    if (getConfigResource().exists())
        properties.load(getConfigResource().getInputStream());
    Set<String> known = new HashSet<String>();
    for (Map.Entry<Object, Object> entry : properties.entrySet()) {
        String username = ((String) entry.getKey()).trim();
        String credentials = ((String) entry.getValue()).trim();
        String roles = null;
        int c = credentials.indexOf(',');
        if (c > 0) {
            roles = credentials.substring(c + 1).trim();
            credentials = credentials.substring(0, c).trim();
        }
        if (username != null && username.length() > 0 && credentials != null && credentials.length() > 0) {
            String[] roleArray = IdentityService.NO_ROLES;
            if (roles != null && roles.length() > 0) {
                roleArray = StringUtil.csvSplit(roles);
            }
            known.add(username);
            Credential credential = Credential.getCredential(credentials);
            Principal userPrincipal = new AbstractLoginService.UserPrincipal(username, credential);
            Subject subject = new Subject();
            subject.getPrincipals().add(userPrincipal);
            subject.getPrivateCredentials().add(credential);
            if (roles != null) {
                for (String role : roleArray) {
                    subject.getPrincipals().add(new AbstractLoginService.RolePrincipal(role));
                }
            }
            subject.setReadOnly();
            _knownUserIdentities.put(username, _identityService.newUserIdentity(subject, userPrincipal, roleArray));
            notifyUpdate(username, credential, roleArray);
        }
    }
    synchronized (_knownUsers) {
        /*
             * if its not the initial load then we want to process removed users
             */
        if (!_firstLoad) {
            Iterator<String> users = _knownUsers.iterator();
            while (users.hasNext()) {
                String user = users.next();
                if (!known.contains(user)) {
                    _knownUserIdentities.remove(user);
                    notifyRemove(user);
                }
            }
        }
        /*
             * reset the tracked _users list to the known users we just processed
             */
        _knownUsers.clear();
        _knownUsers.addAll(known);
    }
    /*
         * set initial load to false as there should be no more initial loads
         */
    _firstLoad = false;
    if (LOG.isDebugEnabled()) {
        LOG.debug("Loaded " + this + " from " + _configPath);
    }
}
Also used : Credential(org.eclipse.jetty.util.security.Credential) Properties(java.util.Properties) Subject(javax.security.auth.Subject) HashMap(java.util.HashMap) Map(java.util.Map) Principal(java.security.Principal) HashSet(java.util.HashSet)

Example 69 with Subject

use of javax.security.auth.Subject in project hazelcast by hazelcast.

the class ExecutorServiceSubmitToPartitionMessageTask method prepareOperation.

@Override
protected Operation prepareOperation() {
    SecurityContext securityContext = clientEngine.getSecurityContext();
    Data callableData = parameters.callable;
    if (securityContext != null) {
        Subject subject = getEndpoint().getSubject();
        Callable callable = serializationService.toObject(parameters.callable);
        callable = securityContext.createSecureCallable(subject, callable);
        callableData = serializationService.toData(callable);
    }
    return new CallableTaskOperation(parameters.name, parameters.uuid, callableData);
}
Also used : SecurityContext(com.hazelcast.security.SecurityContext) Data(com.hazelcast.nio.serialization.Data) Subject(javax.security.auth.Subject) Callable(java.util.concurrent.Callable) CallableTaskOperation(com.hazelcast.executor.impl.operations.CallableTaskOperation)

Example 70 with Subject

use of javax.security.auth.Subject in project hazelcast by hazelcast.

the class DurableExecutorSubmitToPartitionMessageTask method prepareOperation.

@Override
protected Operation prepareOperation() {
    SecurityContext securityContext = clientEngine.getSecurityContext();
    Data callableData = parameters.callable;
    if (securityContext != null) {
        Subject subject = getEndpoint().getSubject();
        Callable callable = serializationService.toObject(parameters.callable);
        callable = securityContext.createSecureCallable(subject, callable);
        callableData = serializationService.toData(callable);
    }
    return new TaskOperation(parameters.name, callableData);
}
Also used : SecurityContext(com.hazelcast.security.SecurityContext) Data(com.hazelcast.nio.serialization.Data) TaskOperation(com.hazelcast.durableexecutor.impl.operations.TaskOperation) Subject(javax.security.auth.Subject) Callable(java.util.concurrent.Callable)

Aggregations

Subject (javax.security.auth.Subject)669 Test (org.testng.annotations.Test)131 Test (org.junit.Test)122 HashMap (java.util.HashMap)120 Principal (java.security.Principal)114 HashSet (java.util.HashSet)109 Set (java.util.Set)82 EntitlementException (com.sun.identity.entitlement.EntitlementException)64 LoginContext (javax.security.auth.login.LoginContext)62 LoginException (javax.security.auth.login.LoginException)49 ConditionDecision (com.sun.identity.entitlement.ConditionDecision)47 ResourceResponse (org.forgerock.json.resource.ResourceResponse)47 RealmContext (org.forgerock.openam.rest.RealmContext)46 Context (org.forgerock.services.context.Context)41 SSOToken (com.iplanet.sso.SSOToken)40 IOException (java.io.IOException)40 ClientContext (org.forgerock.services.context.ClientContext)40 Map (java.util.Map)38 SSOTokenContext (org.forgerock.openam.rest.resource.SSOTokenContext)38 ResourceException (org.forgerock.json.resource.ResourceException)37