Example usage for javax.security.auth Subject getPrincipals

List of usage examples for javax.security.auth Subject getPrincipals

Introduction

In this page you can find the example usage for javax.security.auth Subject getPrincipals.

Prototype

public Set<Principal> getPrincipals() 

Source Link

Document

Return the Set of Principals associated with this Subject .

Usage

From source file:org.wso2.andes.server.security.auth.manager.PrincipalDatabaseAuthenticationManager.java

/**
 * @see org.wso2.andes.server.security.auth.manager.AuthenticationManager#authenticate(String, String)
 *///ww  w  .j  a v  a 2s . com
public AuthenticationResult authenticate(final String username, final String password) {
    try {
        if (_principalDatabase.verifyPassword(username, password.toCharArray())) {
            final Subject subject = new Subject();
            subject.getPrincipals().add(new UsernamePrincipal(username));
            return new AuthenticationResult(subject);
        } else {
            return new AuthenticationResult(AuthenticationStatus.CONTINUE);
        }
    } catch (AccountNotFoundException e) {
        return new AuthenticationResult(AuthenticationStatus.CONTINUE);
    }
}

From source file:org.wso2.andes.server.security.auth.manager.PrincipalDatabaseAuthenticationManager.java

/**
 * @see org.wso2.andes.server.security.auth.manager.AuthenticationManager#authenticate(SaslServer, byte[])
 *//*from w w  w. java 2  s  .  c  om*/
public AuthenticationResult authenticate(SaslServer server, byte[] response) {
    try {
        // Process response from the client
        byte[] challenge = server.evaluateResponse(response != null ? response : new byte[0]);

        if (server.isComplete()) {
            final Subject subject = new Subject();
            subject.getPrincipals().add(new UsernamePrincipal(server.getAuthorizationID()));
            return new AuthenticationResult(subject);
        } else {
            return new AuthenticationResult(challenge, AuthenticationResult.AuthenticationStatus.CONTINUE);
        }
    } catch (SaslException e) {
        return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, e);
    }
}

From source file:org.apache.ws.security.validate.KerberosTokenValidator.java

/**
 * Validate the credential argument. It must contain a non-null BinarySecurityToken. 
 * //from ww  w  .  j  a  v a 2 s .c o m
 * @param credential the Credential to be validated
 * @param data the RequestData associated with the request
 * @throws WSSecurityException on a failed validation
 */
public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    if (credential == null || credential.getBinarySecurityToken() == null) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "noCredential");
    }

    BinarySecurity binarySecurity = credential.getBinarySecurityToken();
    if (!(binarySecurity instanceof KerberosSecurity)) {
        return credential;
    }

    if (log.isDebugEnabled()) {
        try {
            String jaasAuth = System.getProperty("java.security.auth.login.config");
            String krbConf = System.getProperty("java.security.krb5.conf");
            log.debug("KerberosTokenValidator - Using JAAS auth login file: " + jaasAuth);
            log.debug("KerberosTokenValidator - Using KRB conf file: " + krbConf);
        } catch (SecurityException ex) {
            log.debug(ex.getMessage(), ex);
        }
    }

    // Get a TGT from the KDC using JAAS
    LoginContext loginContext = null;
    try {
        if (callbackHandler == null) {
            loginContext = new LoginContext(getContextName());
        } else {
            loginContext = new LoginContext(getContextName(), callbackHandler);
        }
        loginContext.login();
    } catch (LoginException ex) {
        if (log.isDebugEnabled()) {
            log.debug(ex.getMessage(), ex);
        }
        throw new WSSecurityException(WSSecurityException.FAILURE, "kerberosLoginError",
                new Object[] { ex.getMessage() }, ex);
    }
    if (log.isDebugEnabled()) {
        log.debug("Successfully authenticated to the TGT");
    }

    byte[] token = binarySecurity.getToken();

    // Get the service name to use - fall back on the principal
    Subject subject = loginContext.getSubject();
    String service = serviceName;
    if (service == null) {
        Set<Principal> principals = subject.getPrincipals();
        if (principals.isEmpty()) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "kerberosLoginError",
                    new Object[] { "No Client principals found after login" });
        }
        service = principals.iterator().next().getName();
    }

    // Validate the ticket
    KerberosServiceAction action = new KerberosServiceAction(token, service);
    Principal principal = (Principal) Subject.doAs(subject, action);
    if (principal == null) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "kerberosTicketValidationError");
    }
    credential.setPrincipal(principal);
    credential.setSubject(subject);

    // Try to extract the session key from the token if a KerberosTokenDecoder implementation is
    // available
    if (kerberosTokenDecoder != null) {
        kerberosTokenDecoder.clear();
        kerberosTokenDecoder.setToken(token);
        kerberosTokenDecoder.setSubject(subject);
        byte[] sessionKey = kerberosTokenDecoder.getSessionKey();
        credential.setSecretKey(sessionKey);
    }

    if (log.isDebugEnabled()) {
        log.debug("Successfully validated a ticket");
    }

    return credential;
}

From source file:ca.nrc.cadc.web.SearchJobServlet.java

/**
 * Called by the server (via the <code>service</code> method)
 * to allow a servlet to handle a POST request.
 *
 * The HTTP POST method allows the client to send
 * data of unlimited length to the Web server a single time
 * and is useful when posting information such as
 * credit card numbers.//from   ww w  .jav  a2  s  .  co  m
 *
 *When overriding this method, read the request data,
 * write the response headers, get the response's writer or output
 * stream object, and finally, write the response data. It's best
 * to include content type and encoding. When using a
 * <code>PrintWriter</code> object to return the response, set the
 * content type before accessing the <code>PrintWriter</code> object.
 *
 *The servlet container must write the headers before committing the
 * response, because in HTTP the headers must be sent before the
 * response body.
 *
 *Where possible, set the Content-Length header (with the
 * {@link ServletResponse#setContentLength} method),
 * to allow the servlet container to use a persistent connection
 * to return its response to the client, improving performance.
 * The content length is automatically set if the entire response fits
 * inside the response buffer.
 *
 *When using HTTP 1.1 chunked encoding (which means that the response
 * has a Transfer-Encoding header), do not set the Content-Length header.
 *
 *This method does not need to be either safe or idempotent.
 * Operations requested through POST can have side effects for
 * which the user can be held accountable, for example,
 * updating stored data or buying items online.
 *
 *If the HTTP POST request is incorrectly formatted,
 * <code>doPost</code> returns an HTTP "Bad Request" message.
 *
 * @param request  an {@link HttpServletRequest} object that
 *                 contains the request the client has made
 *                 of the servlet
 * @param response an {@link HttpServletResponse} object that
 *                 contains the response the servlet sends
 *                 to the client
 * @throws IOException      if an input or output error is
 *                          detected when the servlet handles
 *                          the request
 * @throws ServletException if the request for the POST
 *                          could not be handled
 * @see ServletOutputStream
 * @see ServletResponse#setContentType
 */
@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    try {
        final Subject subject = AuthenticationUtil.getSubject(request);

        if ((subject == null) || (subject.getPrincipals().isEmpty())) {
            processRequest(request, response);
        } else {
            Subject.doAs(subject, new PrivilegedExceptionAction<Object>() {
                @Override
                public Object run() throws Exception {
                    processRequest(request, response);
                    return null;
                }
            });
        }
    } catch (TransientException ex) {
        // OutputStream not open, write an error response
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        response.addHeader("Retry-After", Integer.toString(ex.getRetryDelay()));
        response.setContentType("text/plain");
        PrintWriter w = response.getWriter();
        w.println("failed to get or persist job state.");
        w.println("   reason: " + ex.getMessage());
        w.close();
    } catch (JobPersistenceException ex) {
        // OutputStream not open, write an error response
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("text/plain");
        PrintWriter w = response.getWriter();
        w.println("failed to get or persist job state.");
        w.println("   reason: " + ex.getMessage());
        w.close();
    } catch (Throwable t) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("text/plain");
        PrintWriter w = response.getWriter();
        w.println("Unable to proceed with job execution.\n");
        w.println("Reason: " + t.getMessage());
        w.close();
    }
}

From source file:org.wso2.andes.server.security.auth.manager.PrincipalDatabaseAuthenticationManagerTest.java

/**
 * Tests that the authenticate method correctly interprets an
 * authentication success.//from  ww  w.  j a va 2s .  c o m
 *
 */
public void testNonSaslAuthenticationSuccess() throws Exception {
    AuthenticationResult result = _manager.authenticate("guest", "guest");
    final Subject subject = result.getSubject();
    assertFalse("Subject should not be set read-only", subject.isReadOnly());
    assertTrue(subject.getPrincipals().contains(new UsernamePrincipal("guest")));
    assertEquals(AuthenticationStatus.SUCCESS, result.getStatus());
}

From source file:net.shibboleth.idp.authn.spnego.impl.SPNEGOAuthnController.java

/**
 * Finish the authentication process successfully.
 * //from  w w  w  .  j a  v  a2s . co  m
 * <p>Sets the attribute {@link ExternalAuthentication#SUBJECT_KEY}.</p>
 * 
 * @param key the conversation key
 * @param httpRequest the HTTP request
 * @param httpResponse the HTTP response
 * @param kerberosPrincipal the Kerberos principal to return
 * 
 * @throws IOException 
 * @throws ExternalAuthenticationException 
 */
private void finishWithSuccess(@Nonnull @NotEmpty final String key,
        @Nonnull final HttpServletRequest httpRequest, @Nonnull final HttpServletResponse httpResponse,
        @Nonnull final KerberosPrincipal kerberosPrincipal)
        throws ExternalAuthenticationException, IOException {

    // Store the user as a username and as a real KerberosPrincipal object.
    final Subject subject = new Subject();
    subject.getPrincipals().add(new UsernamePrincipal(kerberosPrincipal.getName()));
    subject.getPrincipals().add(kerberosPrincipal);

    // Finish the external authentication task and return to the flow.
    httpRequest.setAttribute(ExternalAuthentication.SUBJECT_KEY, subject);
    ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
}

From source file:org.betaconceptframework.astroboa.test.engine.security.CmsLoginTest.java

@Test
public void testAuthenticationTokenIsSameForPermanentKey() {

    Subject subject = new Subject();

    String identity = IdentityPrincipal.ANONYMOUS;
    IdentityPrincipal identityPrincipal = new IdentityPrincipal(identity);
    subject.getPrincipals().add(identityPrincipal);

    String permanentKey = "specialKey";

    String authToken1 = repositoryService.login(TestConstants.TEST_REPOSITORY_ID, subject, permanentKey);

    String authToken2 = repositoryService.login(TestConstants.TEST_REPOSITORY_ID, subject, permanentKey);

    Assert.assertEquals(authToken2, authToken1);

}

From source file:org.betaconceptframework.astroboa.test.engine.security.CmsLoginTest.java

@Test
public void testInvalidPermanentKey() {
    Subject subject = new Subject();

    String identity = "testuser";
    IdentityPrincipal identityPrincipal = new IdentityPrincipal(identity);
    subject.getPrincipals().add(identityPrincipal);

    String permanentKey = "invalidPermanentKey";

    try {/*from   ww  w .j  av a 2  s. c  o m*/
        repositoryService.login(TestConstants.TEST_REPOSITORY_ID, subject, permanentKey);
    } catch (Exception e) {

        Assert.assertTrue((e instanceof CmsException), "Unexpected exception during invalid login");

        Assert.assertEquals(e.getMessage(), "Invalid permanent key " + permanentKey + " for user " + identity
                + " in repository " + TestConstants.TEST_REPOSITORY_ID);
    }

    identity = TestConstants.TEST_USER_NAME;
    subject.getPrincipals().remove(identityPrincipal);
    identityPrincipal = new IdentityPrincipal(identity);
    subject.getPrincipals().add(identityPrincipal);

    try {
        repositoryService.login(TestConstants.TEST_REPOSITORY_ID, subject, permanentKey);
    } catch (Exception e) {

        Assert.assertTrue((e instanceof CmsException), "Unexpected exception during invalid login");

        Assert.assertEquals(e.getMessage(), "Invalid permanent key " + permanentKey + " for user " + identity
                + " in repository " + TestConstants.TEST_REPOSITORY_ID);
    }

}

From source file:net.sourceforge.safr.jaas.permission.PermissionManagerImpl.java

public boolean implies(Permission permission, Subject subject) {
    Principal[] principals = null;
    if (subject == null) {
        principals = new Principal[0];
    } else {/*ww w . ja v  a2s . co  m*/
        principals = new Principal[subject.getPrincipals().size()];
        subject.getPrincipals().toArray(principals);
    }
    return implies(permission, principals);
}

From source file:fi.okm.mpass.idp.authn.impl.OAuth2IdentityTest.java

/**
 * Runs getSubject with prerequisites fulfilled.
 * @throws Exception/*ww w .  j  a v  a2s .c o m*/
 */
protected void testSubjectSuccess(final AbstractOAuth2Identity oAuthId) throws Exception {
    final MockHttpServletRequest httpRequest = initHttpServletRequest();
    final Subject subject = executeGetSubjectWithServer(oAuthId, httpRequest);
    Assert.assertNotNull(subject);
    Assert.assertEquals(subject.getPrincipals().iterator().next().getName(), "mockUser");
}