List of usage examples for javax.security.auth Subject Subject
public Subject()
From source file:org.apache.directory.server.kerberos.kdc.AbstractKerberosITest.java
/** * Obtains a TGT and service tickets for the user. * Also makes some assertions on the received tickets. * * @param encryptionType the encryption type to use * @throws Exception/*from w ww .j av a 2 s. co m*/ */ protected void testObtainTickets(ObtainTicketParameters parameters) throws Exception { setupEnv(parameters); Subject subject = new Subject(); KerberosTestUtils.obtainTGT(subject, USER_UID, USER_PASSWORD); assertEquals(1, subject.getPrivateCredentials().size()); assertEquals(0, subject.getPublicCredentials().size()); KerberosTestUtils.obtainServiceTickets(subject, USER_UID, LDAP_SERVICE_NAME, HOSTNAME); assertEquals(2, subject.getPrivateCredentials().size()); assertEquals(0, subject.getPublicCredentials().size()); for (KerberosTicket kt : subject.getPrivateCredentials(KerberosTicket.class)) { // System.out.println( kt.getClient() ); // System.out.println( kt.getServer() ); // System.out.println( kt.getSessionKeyType() ); assertEquals(parameters.encryptionType.getValue(), kt.getSessionKeyType()); } }
From source file:org.globus.axis.handler.CredentialHandler.java
protected Subject getSubject(MessageContext msgCtx) { Subject subject = (Subject) msgCtx.getProperty(CALLER_SUBJECT); if (subject == null) { subject = new Subject(); msgCtx.setProperty(CALLER_SUBJECT, subject); }/*from w w w.jav a2 s .co m*/ return subject; }
From source file:org.jspresso.hrsample.backend.BackTestStartup.java
private Subject createTestSubject() { Subject testSubject = new Subject(); UserPrincipal p = new UserPrincipal("demo"); testSubject.getPrincipals().add(p);// ww w .j ava 2s . c o m p.putCustomProperty(UserPrincipal.LANGUAGE_PROPERTY, "en"); Group rolesGroup = new SimpleGroup(SecurityHelper.ROLES_GROUP_NAME); rolesGroup.addMember(new SimplePrincipal("administrator")); testSubject.getPrincipals().add(rolesGroup); return testSubject; }
From source file:org.tolven.restful.UserFilter.java
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; HttpSession session = request.getSession(); // LoginContext loginContext = (LoginContext) session.getAttribute("loginContext"); Principal principal = request.getUserPrincipal(); // If we have a principal, then we can proceed if (principal != null) { chain.doFilter(servletRequest, servletResponse); return;//from w ww . j a v a 2 s. co m } // before we accept a password, must ensure that this is a secure session if (!request.isSecure()) { response.setStatus(403); return; } String authorizationHeader = request.getHeader("Authorization"); // See if we have the username/password if (authorizationHeader != null && authorizationHeader.startsWith("Basic ")) { Base64 decoder = new Base64(); byte[] decoded = decoder.decode(authorizationHeader.substring(6).getBytes()); String[] usernamePassword = new String(decoded).split(":"); //WebAuthentication webA = new WebAuthentication(); //boolean loginStatus = webA.login(usernamePassword[0], usernamePassword[1]); //if (!loginStatus) { // response.setStatus(403); // System.out.println( "Login for " + usernamePassword[0] + " - failed"); // return; //} System.out.println("Login for " + usernamePassword[0] + " - succeeded"); //principal = new TolvenPrincipal(usernamePassword[0]); Subject subject = new Subject(); subject.getPrincipals().add(principal); // loginContext = new LoginContext("tolvenLDAP", subject, new CB(usernamePassword[0], usernamePassword[1].toCharArray())); // loginContext.login(); // Success // session.setAttribute("loginContext", loginContext); chain.doFilter(servletRequest, servletResponse); } else { // Ask for password now response.setStatus(401); response.setHeader("WWW-Authenticate", "Basic realm=\"tolvenLDAP\""); } }
From source file:org.apache.storm.security.auth.AutoSSLTest.java
@Test public void testpopulateCredentials() throws Exception { File temp = File.createTempFile("tmp-autossl-test", ".txt"); temp.deleteOnExit();/*from w ww . j a va 2 s.co m*/ List<String> lines = Arrays.asList("The first line", "The second line"); Files.write(temp.toPath(), lines, Charset.forName("UTF-8")); File baseDir = null; try { baseDir = new File("/tmp/autossl-test-" + UUID.randomUUID()); if (!baseDir.mkdir()) { throw new IOException("failed to create base directory"); } AutoSSL assl = new TestAutoSSL(baseDir.getPath()); LOG.debug("base dir is; " + baseDir); Map sslconf = new HashMap(); sslconf.put(AutoSSL.SSL_FILES_CONF, temp.getPath()); assl.prepare(sslconf); Collection<String> sslFiles = assl.getSSLFilesFromConf(sslconf); Map<String, String> creds = new HashMap(); assl.populateCredentials(creds); assertTrue(creds.containsKey(temp.getName())); Subject unusedSubject = new Subject(); assl.populateSubject(unusedSubject, creds); String[] outputFiles = baseDir.list(); assertEquals(1, outputFiles.length); // compare contents of files if (outputFiles.length > 0) { List<String> linesWritten = FileUtils.readLines(new File(baseDir, outputFiles[0]), Charset.forName("UTF-8")); for (String l : linesWritten) { assertTrue(lines.contains(l)); } } } finally { if (baseDir != null) { FileUtils.deleteDirectory(baseDir); } } }
From source file:org.apache.coheigea.cxf.spring.security.authentication.SpringSecurityUTValidator.java
public Credential validate(Credential credential, RequestData data) throws WSSecurityException { if (credential == null || credential.getUsernametoken() == null) { throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "noCredential"); }//from w w w . j a va 2 s .c o m // Validate the UsernameToken UsernameToken usernameToken = credential.getUsernametoken(); String pwType = usernameToken.getPasswordType(); if (log.isDebugEnabled()) { log.debug("UsernameToken user " + usernameToken.getName()); log.debug("UsernameToken password type " + pwType); } if (!WSConstants.PASSWORD_TEXT.equals(pwType)) { if (log.isDebugEnabled()) { log.debug("Authentication failed - digest passwords are not accepted"); } throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION); } if (usernameToken.getPassword() == null) { if (log.isDebugEnabled()) { log.debug("Authentication failed - no password was provided"); } throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION); } // Validate it via Spring Security // Set a Subject up UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken( usernameToken.getName(), usernameToken.getPassword()); Subject subject = new Subject(); subject.getPrincipals().add(authToken); Set<Authentication> authentications = subject.getPrincipals(Authentication.class); Authentication authenticated = null; try { authenticated = authenticationManager.authenticate(authentications.iterator().next()); } catch (AuthenticationException ex) { if (log.isDebugEnabled()) { log.debug(ex.getMessage(), ex); } throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION); } if (!authenticated.isAuthenticated()) { throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION); } for (GrantedAuthority authz : authenticated.getAuthorities()) { System.out.println("Granted: " + authz.getAuthority()); } // Authorize request if (accessDecisionManager != null && !requiredRoles.isEmpty()) { List<ConfigAttribute> attributes = SecurityConfig .createList(requiredRoles.toArray(new String[requiredRoles.size()])); for (ConfigAttribute attr : attributes) { System.out.println("Attr: " + attr.getAttribute()); } accessDecisionManager.decide(authenticated, this, attributes); } credential.setSubject(subject); return credential; }
From source file:org.apache.karaf.jaas.modules.ldap.LdapCacheTest.java
@Test public void testAdminLogin() throws Exception { Properties options = ldapLoginModuleOptions(); LDAPLoginModule module = new LDAPLoginModule(); CallbackHandler cb = new CallbackHandler() { public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (Callback cb : callbacks) { if (cb instanceof NameCallback) { ((NameCallback) cb).setName("admin"); } else if (cb instanceof PasswordCallback) { ((PasswordCallback) cb).setPassword("admin123".toCharArray()); }/* w w w. ja va 2 s . co m*/ } } }; Subject subject = new Subject(); module.initialize(subject, cb, null, options); assertEquals("Precondition", 0, subject.getPrincipals().size()); assertTrue(module.login()); assertTrue(module.commit()); assertEquals(2, subject.getPrincipals().size()); boolean foundUser = false; boolean foundRole = false; for (Principal pr : subject.getPrincipals()) { if (pr instanceof UserPrincipal) { assertEquals("admin", pr.getName()); foundUser = true; } else if (pr instanceof RolePrincipal) { assertEquals("admin", pr.getName()); foundRole = true; } } assertTrue(foundUser); assertTrue(foundRole); assertTrue(module.logout()); assertEquals("Principals should be gone as the user has logged out", 0, subject.getPrincipals().size()); DirContext context = new LDAPCache(new LDAPOptions(options)).open(); // Make "admin" user a member of a new "another" group // dn: cn=admin,ou=groups,dc=example,dc=com // objectClass: top // objectClass: groupOfNames // cn: admin // member: cn=admin,ou=people,dc=example,dc=com Attributes entry = new BasicAttributes(); entry.put(new BasicAttribute("cn", "another")); Attribute oc = new BasicAttribute("objectClass"); oc.add("top"); oc.add("groupOfNames"); entry.put(oc); Attribute mb = new BasicAttribute("member"); mb.add("cn=admin,ou=people,dc=example,dc=com"); entry.put(mb); context.createSubcontext("cn=another,ou=groups,dc=example,dc=com", entry); Thread.sleep(100); module = new LDAPLoginModule(); subject = new Subject(); module.initialize(subject, cb, null, options); assertEquals("Precondition", 0, subject.getPrincipals().size()); assertTrue(module.login()); assertTrue(module.commit()); assertEquals("Postcondition", 3, subject.getPrincipals().size()); }
From source file:org.apache.karaf.jaas.modules.ldap.LdapLoginModuleTest.java
@Test public void testAdminLogin() throws Exception { Properties options = ldapLoginModuleOptions(); LDAPLoginModule module = new LDAPLoginModule(); CallbackHandler cb = new CallbackHandler() { public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (Callback cb : callbacks) { if (cb instanceof NameCallback) { ((NameCallback) cb).setName("admin"); } else if (cb instanceof PasswordCallback) { ((PasswordCallback) cb).setPassword("admin123".toCharArray()); }/*from w ww . j a v a 2 s. co m*/ } } }; Subject subject = new Subject(); module.initialize(subject, cb, null, options); assertEquals("Precondition", 0, subject.getPrincipals().size()); assertTrue(module.login()); assertTrue(module.commit()); assertEquals(2, subject.getPrincipals().size()); boolean foundUser = false; boolean foundRole = false; for (Principal pr : subject.getPrincipals()) { if (pr instanceof UserPrincipal) { assertEquals("admin", pr.getName()); foundUser = true; } else if (pr instanceof RolePrincipal) { assertEquals("admin", pr.getName()); foundRole = true; } } assertTrue(foundUser); assertTrue(foundRole); assertTrue(module.logout()); assertEquals("Principals should be gone as the user has logged out", 0, subject.getPrincipals().size()); }
From source file:org.apache.karaf.jaas.modules.ldap.LdapCaseInsensitiveDNTest.java
@Test public void testCaseInsensitiveDN() throws Exception { Properties options = ldapLoginModuleOptions(); LDAPLoginModule module = new LDAPLoginModule(); CallbackHandler cb = new CallbackHandler() { public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (Callback cb : callbacks) { if (cb instanceof NameCallback) { ((NameCallback) cb).setName("admin"); } else if (cb instanceof PasswordCallback) { ((PasswordCallback) cb).setPassword("admin123".toCharArray()); }//from w ww . j av a 2 s.co m } } }; Subject subject = new Subject(); module.initialize(subject, cb, null, options); assertEquals("Precondition", 0, subject.getPrincipals().size()); assertTrue(module.login()); assertTrue(module.commit()); assertEquals(2, subject.getPrincipals().size()); boolean foundUser = false; boolean foundRole = false; for (Principal pr : subject.getPrincipals()) { if (pr instanceof UserPrincipal) { assertEquals("admin", pr.getName()); foundUser = true; } else if (pr instanceof RolePrincipal) { assertEquals("admin", pr.getName()); foundRole = true; } } assertTrue(foundUser); assertTrue(foundRole); assertTrue(module.logout()); assertEquals("Principals should be gone as the user has logged out", 0, subject.getPrincipals().size()); }
From source file:org.betaconceptframework.astroboa.resourceapi.utility.ContentApiUtils.java
public static Subject createSubjectForSystemUserAndItsRoles(String cmsRepositoryId) { Subject subject = new Subject(); //System identity subject.getPrincipals().add(new IdentityPrincipal(IdentityPrincipal.SYSTEM)); //Load default roles for SYSTEM USER //Must return at list one group named "Roles" in order to be Group rolesPrincipal = new CmsGroup(AstroboaPrincipalName.Roles.toString()); for (CmsRole cmsRole : CmsRole.values()) { rolesPrincipal.addMember(new CmsPrincipal(CmsRoleAffiliationFactory.INSTANCE .getCmsRoleAffiliationForRepository(cmsRole, cmsRepositoryId))); }//from w w w . j a v a 2 s . co m subject.getPrincipals().add(rolesPrincipal); return subject; }