Example usage for javax.security.auth Subject Subject

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

Introduction

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

Prototype

public Subject() 

Source Link

Document

Create an instance of a Subject with an empty Set of Principals and empty Sets of public and private credentials.

Usage

From source file:backtype.storm.blobstore.BlobStoreTest.java

public static Subject getNimbusSubject() {
    Subject nimbus = new Subject();
    nimbus.getPrincipals().add(new NimbusPrincipal());
    return nimbus;
}

From source file:scratch.cucumber.example.security.spring.UserAuthenticationTest.java

@Test
public void Can_create_a_user_authentication() {

    final User user = mock(User.class);
    final String username = someString();
    final String password = someString();
    final Boolean authenticated = someBoolean();

    // Given//  w  ww .  j a v  a 2 s .c om
    given(user.getUsername()).willReturn(username);
    given(user.getPassword()).willReturn(password);

    // When
    final UserAuthentication actual = new UserAuthentication(user);
    actual.setAuthenticated(authenticated);

    // Then
    assertPropertyReflectionEquals("user", user, actual);
    assertThat(actual.getName(), equalTo(username));
    assertThat(actual.getPrincipal(), equalTo(username));
    assertThat(actual.getCredentials(), equalTo(password));
    assertThat(actual.getAuthorities(), empty());
    assertThat(actual.isAuthenticated(), equalTo(authenticated));
    assertThat(actual.implies(new Subject()), equalTo(false));

    final UserDetails details = actual.getDetails();

    assertThat(details.getUsername(), equalTo(username));
    assertThat(details.getPassword(), equalTo(password));
    assertThat(details.getAuthorities(), empty());
    assertThat(details.isAccountNonExpired(), equalTo(true));
    assertThat(details.isAccountNonLocked(), equalTo(true));
    assertThat(details.isCredentialsNonExpired(), equalTo(true));
    assertThat(details.isEnabled(), equalTo(true));
}

From source file:org.apache.coheigea.cxf.x509.authorization.X509AuthorizationValidator.java

public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    Credential validatedCredential = super.validate(credential, data);

    // Validate the Certificate
    X509Certificate[] certs = validatedCredential.getCertificates();
    if (certs == null || certs.length == 0) {
        if (log.isDebugEnabled()) {
            log.debug("No X.509 Certificates are found");
        }// www  . jav a2s . com
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
    }

    Principal principal = validatedCredential.getPrincipal();
    // Mock up a Subject
    Subject subject = new Subject();
    subject.getPrincipals().add(principal);
    subject.getPrincipals().add(new SimpleGroup("employee"));
    if (principal.getName().startsWith("CN=Client,O=Apache")) {
        subject.getPrincipals().add(new SimpleGroup("boss"));
    }
    subject.setReadOnly();
    credential.setSubject(subject);

    return credential;
}

From source file:org.josso.auth.AuthenticatorImpl.java

/**
 * Validates user identity.  Populates the Subject with Principal and Credential information.
 *
 * @param credentials the credentials to be checked
 * @param schemeName  the authentication scheme to be used to check the supplied credentials.
 *///from ww w .  j  av a2s . c  om
public Subject check(Credential[] credentials, String schemeName) throws SSOAuthenticationException {

    // Initialize the AuthenticationScheme
    Subject s = new Subject();
    AuthenticationScheme scheme = getScheme(schemeName);
    scheme.initialize(credentials, s);

    if (scheme.authenticate()) {
        scheme.confirm();
        _authCount++;
    } else {
        scheme.cancel();
        _authFailures++;

        throw new AuthenticationFailureException(scheme.getPrincipal().getName());
    }

    return s;
}

From source file:org.infoscoop.admin.web.PreviewImpersonationFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    request.setAttribute(IS_PREVIEW, Boolean.TRUE);

    Subject previewUser = new Subject();

    List<String> principals = new ArrayList<String>();

    String uidParam = request.getParameter(ISPrincipal.UID_PRINCIPAL);
    if (uidParam != null) {
        principals.add(ISPrincipal.UID_PRINCIPAL);
        principals.add(uidParam);//from   w  w w.  j a  va  2 s  . c  o m
        previewUser.getPrincipals().add(new ISPrincipal(ISPrincipal.UID_PRINCIPAL, uidParam));
    }
    for (PrincipalDef def : SessionCreateConfig.getInstance().getPrincipalDefs()) {
        String[] principalValues = request.getParameterValues(def.getType());
        if (principalValues != null) {
            for (int i = 0; i < principalValues.length; i++) {
                if (log.isInfoEnabled())
                    log.info("Set preview principal: PrincipalType=" + def.getType() + ", name="
                            + principalValues[i] + ".");

                principals.add(def.getType());
                principals.add(principalValues[i]);
                previewUser.getPrincipals().add(new ISPrincipal(def.getType(), principalValues[i]));
            }
        }
    }

    // Principal retrieved from AccountManager set AuthenticationService
    AuthenticationService service = AuthenticationService.getInstance();
    IAccountManager manager = null;
    if (service != null)
        manager = service.getAccountManager();
    if (manager != null) {
        for (PrincipalDef def : manager.getPrincipalDefs()) {
            String roleType = def.getType();
            String[] principalValues = request.getParameterValues(roleType);

            for (int i = 0; principalValues != null && i < principalValues.length; i++) {
                if (log.isInfoEnabled())
                    log.info("Set preview principal: PrincipalType=" + roleType + ", name=" + principalValues[i]
                            + ".");
                principals.add(def.getType());
                principals.add(principalValues[i]);
                previewUser.getPrincipals().add(new ISPrincipal(roleType, principalValues[i]));
            }
        }
    }

    request.setAttribute(PRINCIPAL_PARAMS, principals);

    SetPrincipalHttpServletRequest reqwrapper = new SetPrincipalHttpServletRequest((HttpServletRequest) request,
            previewUser);
    filterChain.doFilter(reqwrapper, response);
}

From source file:com.muk.services.processor.BasicAuthPrincipalProcessor.java

@Override
public void process(Exchange exchange) throws Exception {
    @SuppressWarnings("unchecked")
    final List<Header> httpHeaders = exchange.getIn().getHeader("org.restlet.http.headers", List.class);

    String userpass = "bad:creds";
    for (final Header header : httpHeaders) {
        if (header.getName().toLowerCase().equals(HttpHeaders.AUTHORIZATION.toLowerCase())) {
            userpass = new String(Base64.decodeBase64(
                    (StringUtils.substringAfter(header.getValue(), " ").getBytes(StandardCharsets.UTF_8))),
                    StandardCharsets.UTF_8);
            break;
        }/* w  w  w . j a  va2s.c o  m*/
    }

    final String[] tokens = userpass.split(":");

    // create an Authentication object
    // build a new bearer token type
    final UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(tokens[0],
            tokens[1]);

    // wrap it in a Subject
    final Subject subject = new Subject();
    subject.getPrincipals().add(authToken);

    // place the Subject in the In message
    exchange.getIn().setHeader(Exchange.AUTHENTICATION, subject);
}

From source file:org.atricore.idbus.kernel.main.authn.AuthenticatorImpl.java

/**
 * Validates user identity.  Populates the Subject with Principal and Credential information.
 *
 * @param credentials the credentials to be checked
 * @param schemeName  the authentication scheme to be used to check the supplied credentials.
 *///from w w  w  .  jav  a  2s .c o m
public Subject check(Credential[] credentials, String schemeName) throws SSOAuthenticationException {

    // Initialize the AuthenticationScheme
    Subject s = new Subject();

    List<AuthenticationScheme> schemes = getSchemes(schemeName);
    Set<SSOPolicyEnforcementStatement> ssoPolicies = new HashSet<SSOPolicyEnforcementStatement>();
    String lastPrincipal = null;

    for (AuthenticationScheme scheme : schemes) {

        if (logger.isTraceEnabled())
            logger.trace("Authenticating with " + scheme);

        scheme.initialize(credentials, s);

        if (scheme.authenticate()) {
            // If authentication succeeds, return the subject.
            scheme.confirm();
            _authCount++;

            // Add all SSO Policies to authenticated Subject
            s.getPrincipals().addAll(scheme.getSSOPolicies());
            return s;
        }

        scheme.cancel();
        if (scheme.getSSOPolicies() != null) {
            ssoPolicies.addAll(scheme.getSSOPolicies());
        }
        if (scheme.getPrincipal() != null)
            lastPrincipal = scheme.getPrincipal().getName();

    }
    // Send SSO Policies with Authn error
    _authFailures++;
    throw new AuthenticationFailureException(lastPrincipal, lastPrincipal, ssoPolicies);

}

From source file:org.apache.hadoop.security.SecureClientLogin.java

public synchronized static Subject loginUserWithPassword(String user, String password) throws IOException {
    String tmpPass = password;/*w  ww  .  jav a 2  s . com*/
    try {
        Subject subject = new Subject();
        SecureClientLoginConfiguration loginConf = new SecureClientLoginConfiguration(false, user, password);
        LoginContext login = new LoginContext("hadoop-keytab-kerberos", subject, null, loginConf);
        subject.getPrincipals().add(new User(user, AuthenticationMethod.KERBEROS, login));
        login.login();
        return login.getSubject();
    } catch (LoginException le) {
        throw new IOException("Login failure for " + user + " using password " + tmpPass.replaceAll(".", "*"),
                le);
    }
}

From source file:org.josso.auth.scheme.test.RememberMeAuthSchemeTest.java

@Test
public void testRememberMe() throws Exception {

    RememberMeAuthScheme scheme = (RememberMeAuthScheme) applicationContext
            .getBean("josso-rememberme-authentication");
    assert scheme != null : "No authentication scheme configured";

    String tokenValue = scheme.getRemembermeTokenForUser("user1");

    Credential token = scheme.newCredential(RememberMeAuthScheme.REMEMBER_ME_TOKEN_CREDENTIAL_NAME, tokenValue);
    assert token != null : "No 'token' Credential created by provider";

    Credential username = scheme.newCredential(RememberMeAuthScheme.USERNAME_CREDENTIAL_NAME, "user1");
    assert username != null : "No 'username' Credential created by provider";

    Subject s = new Subject();
    scheme.initialize(new Credential[] { token, username }, s);

    scheme.authenticate();/*from  www . j  av a2s. c  om*/
    scheme.confirm();

    assert s.getPrincipals().size() == 1 : "Expected one principal, got : " + s.getPrincipals().size();

    Principal user = s.getPrincipals().iterator().next();
    assert user.getName().equals("user1") : "Expected user1 principal, got : " + user.getName();
}

From source file:uk.org.openeyes.oink.security.TestSimpleIdentityService.java

@Test
public void testGetUserIdForValidSubject() {
    SimpleIdentityService identityService = new SimpleIdentityService();
    Subject s = new Subject();
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("bob@moorfields",
            "password");
    s.getPrincipals().add(token);/*  w  ww  .ja v a  2 s  . com*/

    String user = identityService.getUserId(s);

    String expectedUser = "bob";
    assertEquals(expectedUser, user);
}