List of usage examples for javax.security.auth Subject Subject
public Subject(boolean readOnly, Set<? extends Principal> principals, Set<?> pubCredentials, Set<?> privCredentials)
From source file:org.elasticsearch.xpack.security.authc.kerberos.SpnegoHttpClientConfigCallbackHandler.java
/** * If logged in {@link LoginContext} is not available, it attempts login and * returns {@link LoginContext}/* w w w . jav a 2s . co m*/ * * @return {@link LoginContext} * @throws PrivilegedActionException */ public synchronized LoginContext login() throws PrivilegedActionException { if (this.loginContext == null) { AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> { final Subject subject = new Subject(false, Collections.singleton(new KerberosPrincipal(userPrincipalName)), Collections.emptySet(), Collections.emptySet()); Configuration conf = null; final CallbackHandler callback; if (password != null) { conf = new PasswordJaasConf(userPrincipalName, enableDebugLogs); callback = new KrbCallbackHandler(userPrincipalName, password); } else { conf = new KeytabJaasConf(userPrincipalName, keytabPath, enableDebugLogs); callback = null; } loginContext = new LoginContext(CRED_CONF_NAME, subject, callback, conf); loginContext.login(); return null; }); } return loginContext; }
From source file:org.apache.sentry.api.service.thrift.TestSentryWebServerWithKerberos.java
@Test public void testPingWithCaseSensitiveUser() throws Exception { // USER1 is present in the list of users who are allowed to connect to sentry web ui. String userPrinciple = "user1/" + SentryServiceIntegrationBase.SERVER_HOST; String userKerberosName = userPrinciple + "@" + SentryServiceIntegrationBase.REALM; Subject userSubject = new Subject(false, Sets.newHashSet(new KerberosPrincipal(userKerberosName)), new HashSet<Object>(), new HashSet<Object>()); File userKeytab = new File(SentryServiceIntegrationBase.kdcWorkDir, "user1.keytab"); SentryServiceIntegrationBase.kdc.createPrincipal(userKeytab, userPrinciple); LoginContext userLoginContext = new LoginContext("", userSubject, null, KerberosConfiguration.createClientConfig(userKerberosName, userKeytab)); userLoginContext.login();// w ww .j a v a 2 s. c o m Subject.doAs(userLoginContext.getSubject(), new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { final URL url = new URL("http://" + SentryServiceIntegrationBase.SERVER_HOST + ":" + SentryServiceIntegrationBase.webServerPort + "/ping"); try { new AuthenticatedURL(new KerberosAuthenticator()).openConnection(url, new AuthenticatedURL.Token()); fail("Login with user1 should fail"); } catch (AuthenticationException e) { String expectedError = "status code: 403"; if (!exceptionContainsMessage(e, expectedError)) { LOG.error("UnexpectedError: " + e.getMessage(), e); fail("UnexpectedError: " + e.getMessage()); } } return null; } }); }
From source file:org.pentaho.di.trans.ael.websocket.SessionConfigurator.java
private Subject getServiceSubject(ClientLoginConfig loginConfig) throws Exception { Set<Principal> princ = new HashSet<>(1); princ.add(new KerberosPrincipal(this.principal)); Subject sub = new Subject(false, princ, new HashSet(), new HashSet()); loginContext = new LoginContext("", sub, null, loginConfig); loginContext.login();/*www. j a va2 s. c o m*/ return loginContext.getSubject(); }
From source file:com.lucidworks.security.authentication.server.KerberosAuthenticationHandler.java
/** * Initializes the authentication handler instance. * <p/>/*from w w w .j a va 2 s. c o m*/ * It creates a Kerberos context using the principal and keytab specified in the configuration. * <p/> * This method is invoked by the {@link AuthenticationFilter#init} method. * * @param config configuration properties to initialize the handler. * * @throws ServletException thrown if the handler could not be initialized. */ @Override public void init(Properties config) throws ServletException { try { principal = config.getProperty(PRINCIPAL, principal); if (principal == null || principal.trim().length() == 0) { throw new ServletException("Principal not defined in configuration"); } keytab = config.getProperty(KEYTAB, keytab); if (keytab == null || keytab.trim().length() == 0) { throw new ServletException("Keytab not defined in configuration"); } if (!new File(keytab).exists()) { throw new ServletException("Keytab does not exist: " + keytab); } String nameRules = config.getProperty(NAME_RULES, null); if (nameRules != null) { KerberosName.setRules(nameRules); } Set<Principal> principals = new HashSet<Principal>(); principals.add(new KerberosPrincipal(principal)); Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>()); KerberosConfiguration kerberosConfiguration = new KerberosConfiguration(keytab, principal); LOG.info("Login using keytab " + keytab + ", for principal " + principal); loginContext = new LoginContext("", subject, null, kerberosConfiguration); loginContext.login(); Subject serverSubject = loginContext.getSubject(); try { gssManager = Subject.doAs(serverSubject, new PrivilegedExceptionAction<GSSManager>() { @Override public GSSManager run() throws Exception { return GSSManager.getInstance(); } }); } catch (PrivilegedActionException ex) { throw ex.getException(); } LOG.info("Initialized, principal [{}] from keytab [{}]", principal, keytab); } catch (Exception ex) { throw new ServletException(ex); } }
From source file:org.springframework.security.kerberos.client.KerberosRestTemplate.java
/** * Setup the {@link LoginContext} with credentials and options for authentication against kerberos. * * @return the login context//from w ww.j a va2s. co m */ private LoginContext buildLoginContext() throws LoginException { ClientLoginConfig loginConfig = new ClientLoginConfig(keyTabLocation, userPrincipal, password, loginOptions); Set<Principal> princ = new HashSet<Principal>(1); princ.add(new KerberosPrincipal(userPrincipal)); Subject sub = new Subject(false, princ, new HashSet<Object>(), new HashSet<Object>()); CallbackHandler callbackHandler = new CallbackHandlerImpl(userPrincipal, password); LoginContext lc = new LoginContext("", sub, callbackHandler, loginConfig); return lc; }
From source file:org.onehippo.forge.security.support.springsecurity.container.SpringSecurityValve.java
@Override public void invoke(ValveContext context) throws ContainerException { HttpServletRequest request = context.getServletRequest(); Principal userPrincipal = request.getUserPrincipal(); // If user has not been authenticated yet by any mechanism, then simply move to the next valve chain. if (userPrincipal == null) { if (log.isDebugEnabled()) { log.debug("No user principal found. Skipping SpringSecurityValve..."); }//from www . jav a 2 s . c o m context.invokeNext(); return; } // Get the current subject from http session if exists. HttpSession session = request.getSession(false); Subject subject = (session != null ? (Subject) session.getAttribute(ContainerConstants.SUBJECT_ATTR_NAME) : null); // If a subject has been established already (normally by HST-2's SecurityValve), then simply move to the next valve chain. if (subject != null) { if (log.isDebugEnabled()) { log.debug("Already subject has been created somewhere before. Skipping SpringSecurityValve..."); } context.invokeNext(); return; } // Get Spring Security Context object from thread local. SecurityContext securityContext = SecurityContextHolder.getContext(); // If there's no Spring Security Context object, then just move to next valve chain. if (securityContext == null) { if (log.isDebugEnabled()) { log.debug("Spring Security hasn't established security context. Skipping SpringSecurityValve..."); } context.invokeNext(); return; } // Get the Authentication object from the Spring Security context object. Authentication authentication = securityContext.getAuthentication(); // If there's no Authentication object, it's really weird, so leave warning logs, and move to next valve chain. if (authentication == null) { if (log.isWarnEnabled()) { log.warn( "Spring Security hasn't establish security context with authentication object. Skipping SpringSecurityValve..."); } context.invokeNext(); return; } // Get principal object from the Spring Security authentication object. Object springSecurityPrincipal = authentication.getPrincipal(); // We expect the principal is instance of UserDetails. Otherwise, let's skip it and leave warning logs. if (!(springSecurityPrincipal instanceof UserDetails)) { if (log.isWarnEnabled()) { log.warn( "Spring Security hasn't establish security context with UserDetails object. We don't support non UserDetails authentication. Skipping SpringSecurityValve..."); } context.invokeNext(); return; } // Cast principal instance to UserDetails UserDetails userDetails = (UserDetails) springSecurityPrincipal; // Create HST-2 TransientUser principal from the user principal. User user = new TransientUser(userPrincipal.getName()); // Add both the existing user principal and new HST-2 user transient user principal // just for the case when HST-2 can inspect the user principals for some reasons. Set<Principal> principals = new HashSet<Principal>(); principals.add(userPrincipal); principals.add(user); // Retrieve all the granted authorities from the UserDetail instance // and convert it into HST-2 TransientRoles. for (GrantedAuthority authority : userDetails.getAuthorities()) { String authorityName = authority.getAuthority(); if (!StringUtils.isEmpty(authorityName)) { principals.add(new TransientRole(authorityName)); } } Set<Object> pubCred = new HashSet<Object>(); Set<Object> privCred = new HashSet<Object>(); // If the flag is turned on, then store JCR credentials as well // just for the case the site is expected to use session stateful JCR sessions per authentication. if (storeSubjectRepositoryCredentials) { Credentials subjectRepoCreds = null; // Note: password should be null by default from some moment after Spring Security version upgraded a while ago. // if password is null, let's store a dummy password instead. if (userDetails.getPassword() != null) { subjectRepoCreds = new SimpleCredentials(userDetails.getUsername(), userDetails.getPassword().toCharArray()); } else { subjectRepoCreds = new SimpleCredentials(userDetails.getUsername(), DUMMY_CHARS); } privCred.add(subjectRepoCreds); } subject = new Subject(true, principals, pubCred, privCred); // Save the created subject as http session attribute which can be read by HST-2 SecurityValve in the next valve chain. request.getSession(true).setAttribute(ContainerConstants.SUBJECT_ATTR_NAME, subject); context.invokeNext(); }
From source file:ca.nrc.cadc.vos.server.NodeDAOTest.java
public NodeDAOTest() throws Exception { this.runID = "test" + new Date().getTime(); log.debug("runID = " + runID); this.principal = new X500Principal(NODE_OWNER); this.principal2 = new X500Principal(NODE_OWNER2); Set<Principal> pset = new HashSet<Principal>(); Set<Principal> pset2 = new HashSet<Principal>(); pset.add(principal);//from ww w . j a v a2 s. co m pset2.add(principal2); this.owner = new Subject(true, pset, new HashSet(), new HashSet()); this.owner2 = new Subject(true, pset2, new HashSet(), new HashSet()); try { DBConfig dbConfig = new DBConfig(); ConnectionConfig connConfig = null; try { connConfig = dbConfig.getConnectionConfig(SERVER, DATABASE); } catch (NoSuchElementException e) { log.warn("Skipping itegration tests because there is no database entry in ~/.dbrc"); org.junit.Assume.assumeTrue(false); } this.dataSource = DBUtil.getDataSource(connConfig); this.nodeSchema = new NodeSchema("Node", "NodeProperty", true); // TOP // cleanup from old runs //JdbcTemplate jdbc = new JdbcTemplate(dataSource); //jdbc.update("DELETE FROM " + nodeSchema.propertyTable); //jdbc.update("DELETE FROM " + nodeSchema.nodeTable); this.nodeDAO = new NodeDAO(dataSource, nodeSchema, VOS_AUTHORITY, new X500IdentityManager(), DELETED_NODES); } catch (FileNotFoundException e) { log.warn("Skipping itegration tests because there is no ~/.dbrc file."); org.junit.Assume.assumeTrue(false); } catch (NoSuchElementException e) { log.warn("Skipping itegration tests because there is no database entry in ~/.dbrc"); org.junit.Assume.assumeTrue(false); } catch (Exception ex) { // make sure it gets fully dumped log.error("SETUP FAILED", ex); throw ex; } }
From source file:org.apache.lens.client.SpnegoClientFilter.java
private LoginContext buildLoginContext() throws LoginException { ClientLoginConfig loginConfig = new ClientLoginConfig(keyTabLocation, userPrincipal); Subject subject = null;/* w w w .j a va 2 s .co m*/ if (StringUtils.isNotBlank(keyTabLocation) && StringUtils.isNotBlank(userPrincipal)) { Set<Principal> princ = new HashSet<>(1); princ.add(new KerberosPrincipal(userPrincipal)); subject = new Subject(false, princ, new HashSet<>(), new HashSet<>()); } LoginContext lc = new LoginContext("", subject, null, loginConfig); return lc; }
From source file:nl.nn.adapterframework.util.CredentialFactory.java
protected void getCredentialsFromAlias() { if (!gotCredentials && StringUtils.isNotEmpty(getAlias())) { try {/*from w w w .ja v a 2 s . c om*/ Set principals = new HashSet(); Set publicCredentials = new HashSet(); Set privateCredentials = new HashSet(); Principal p = new IbisPrincipal(); principals.add(p); Subject initialSubject = new Subject(false, principals, publicCredentials, privateCredentials); String loginConfiguration = AppConstants.getInstance().getProperty("PrincipalMapping", "DefaultPrincipalMapping"); LoginContext lc = new LoginContext(loginConfiguration, initialSubject, this); lc.login(); Subject s = lc.getSubject(); //showSet(s.getPrincipals(),"principals"); //showSet(s.getPublicCredentials(),"PublicCredentials"); //showSet(s.getPrivateCredentials(),"PrivateCredentials"); //Object pwcred=Subject.doAsPrivileged(s,new PasswordGetter(s),AccessController.getContext()); //Object pwcred=AccessController.doPrivileged(new PasswordGetter(s)); Object pwcred = s.getPrivateCredentials().toArray()[0]; setUsername(ClassUtils.invokeStringGetter(pwcred, "getUserName")); setPassword(invokeCharArrayGetter(pwcred, "getPassword")); gotCredentials = true; } catch (Exception e) { if (!useFallback) { NoSuchElementException nsee = new NoSuchElementException( "cannot obtain credentials from authentication alias [" + getAlias() + "]"); nsee.initCause(e); throw nsee; } log.error("exception obtaining credentials for alias [" + getAlias() + "]", e); String usernameProp = "alias." + getAlias() + ".username"; String passwordProp = "alias." + getAlias() + ".password"; log.info("trying to solve Authentication Alias from application properties [" + usernameProp + "] and [" + passwordProp + "]"); setUsername(AppConstants.getInstance().getProperty(usernameProp, username)); setPassword(AppConstants.getInstance().getProperty(passwordProp, password)); } } }
From source file:org.apache.hadoop.registry.secure.AbstractSecureRegistryTest.java
/** * Log in, defaulting to the client context * @param principal principal/*from w w w . j av a 2s.c om*/ * @param context context * @param keytab keytab * @return the logged in context * @throws LoginException failure to log in * @throws FileNotFoundException no keytab */ protected LoginContext login(String principal, String context, File keytab) throws LoginException, FileNotFoundException { LOG.info("Logging in as {} in context {} with keytab {}", principal, context, keytab); if (!keytab.exists()) { throw new FileNotFoundException(keytab.getAbsolutePath()); } Set<Principal> principals = new HashSet<Principal>(); principals.add(new KerberosPrincipal(principal)); Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>()); LoginContext login; login = new LoginContext(context, subject, null, KerberosConfiguration.createClientConfig(principal, keytab)); login.login(); return login; }