List of usage examples for javax.security.auth Subject Subject
public Subject()
From source file:com.buaa.cfs.security.UserGroupInformation.java
/** * Log a user in from a keytab file. Loads a user identity from a keytab file and login them in. This new user does * not affect the currently logged-in user. * * @param user the principal name to load from the keytab * @param path the path to the keytab file * * @throws IOException if the keytab file can't be read *///from www . j av a 2 s . c om public synchronized static UserGroupInformation loginUserFromKeytabAndReturnUGI(String user, String path) throws IOException { if (!isSecurityEnabled()) return UserGroupInformation.getCurrentUser(); String oldKeytabFile = null; String oldKeytabPrincipal = null; long start = 0; try { oldKeytabFile = keytabFile; oldKeytabPrincipal = keytabPrincipal; keytabFile = path; keytabPrincipal = user; Subject subject = new Subject(); LoginContext login = newLoginContext(HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, subject, new HadoopConfiguration()); start = Time.now(); login.login(); // metrics.loginSuccess.add(Time.now() - start); UserGroupInformation newLoginUser = new UserGroupInformation(subject); newLoginUser.setLogin(login); newLoginUser.setAuthenticationMethod(AuthenticationMethod.KERBEROS); return newLoginUser; } catch (LoginException le) { if (start > 0) { // metrics.loginFailure.add(Time.now() - start); } throw new IOException("Login failure for " + user + " from keytab " + path, le); } finally { if (oldKeytabFile != null) keytabFile = oldKeytabFile; if (oldKeytabPrincipal != null) keytabPrincipal = oldKeytabPrincipal; } }
From source file:com.mirth.connect.connectors.http.HttpReceiver.java
private ConstraintSecurityHandler createSecurityHandler(Handler handler) throws Exception { final Authenticator authenticator = authenticatorProvider.getAuthenticator(); final String authMethod; switch (authProps.getAuthType()) { case BASIC:// w w w .j a va 2 s. co m authMethod = Constraint.__BASIC_AUTH; break; case DIGEST: authMethod = Constraint.__DIGEST_AUTH; break; default: authMethod = "customauth"; } Constraint constraint = new Constraint(); constraint.setName(authMethod); constraint.setRoles(new String[] { "user" }); constraint.setAuthenticate(true); ConstraintMapping constraintMapping = new ConstraintMapping(); constraintMapping.setConstraint(constraint); constraintMapping.setPathSpec("/*"); ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler(); securityHandler.setAuthenticator(new org.eclipse.jetty.security.Authenticator() { @Override public void setConfiguration(AuthConfiguration configuration) { } @Override public String getAuthMethod() { return authMethod; } @Override public void prepareRequest(ServletRequest request) { } @Override public Authentication validateRequest(final ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; String remoteAddress = StringUtils.trimToEmpty(request.getRemoteAddr()); int remotePort = request.getRemotePort(); String localAddress = StringUtils.trimToEmpty(request.getLocalAddr()); int localPort = request.getLocalPort(); String protocol = StringUtils.trimToEmpty(request.getProtocol()); String method = StringUtils.trimToEmpty(request.getMethod()); String requestURI = StringUtils.trimToEmpty(request.getRequestURI()); Map<String, List<String>> headers = HttpMessageConverter.convertFieldEnumerationToMap(request); Map<String, List<String>> queryParameters = new LinkedHashMap<String, List<String>>(); for (Entry<String, String[]> entry : req.getParameterMap().entrySet()) { queryParameters.put(entry.getKey(), Arrays.asList(entry.getValue())); } EntityProvider entityProvider = new EntityProvider() { @Override public byte[] getEntity() throws IOException { byte[] entity = (byte[]) req.getAttribute(ATTRIBUTE_NAME); if (entity == null) { entity = IOUtils.toByteArray(req.getInputStream()); req.setAttribute(ATTRIBUTE_NAME, entity); } return entity; } }; RequestInfo requestInfo = new RequestInfo(remoteAddress, remotePort, localAddress, localPort, protocol, method, requestURI, headers, queryParameters, entityProvider, configuration.getRequestInformation(request)); try { AuthenticationResult result = authenticator.authenticate(requestInfo); for (Entry<String, List<String>> entry : result.getResponseHeaders().entrySet()) { if (StringUtils.isNotBlank(entry.getKey()) && entry.getValue() != null) { for (int i = 0; i < entry.getValue().size(); i++) { if (i == 0) { response.setHeader(entry.getKey(), entry.getValue().get(i)); } else { response.addHeader(entry.getKey(), entry.getValue().get(i)); } } } } switch (result.getStatus()) { case CHALLENGED: response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return org.eclipse.jetty.server.Authentication.SEND_CONTINUE; case SUCCESS: Principal userPrincipal = new KnownUser(StringUtils.trimToEmpty(result.getUsername()), null); Subject subject = new Subject(); subject.getPrincipals().add(userPrincipal); return new UserAuthentication(getAuthMethod(), new DefaultUserIdentity(subject, userPrincipal, new String[] { "user" })); case FAILURE: default: response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return org.eclipse.jetty.server.Authentication.SEND_FAILURE; } } catch (Throwable t) { logger.error("Error in HTTP authentication for " + connectorProperties.getName() + " (" + connectorProperties.getName() + " \"Source\" on channel " + getChannelId() + ").", t); eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), null, ErrorEventType.DESTINATION_CONNECTOR, "Source", connectorProperties.getName(), "Error in HTTP authentication for " + connectorProperties.getName(), t)); throw new ServerAuthException(t); } } @Override public boolean secureResponse(ServletRequest request, ServletResponse response, boolean mandatory, User validatedUser) throws ServerAuthException { return true; } }); securityHandler.addConstraintMapping(constraintMapping); securityHandler.setHandler(handler); return securityHandler; }
From source file:com.buaa.cfs.security.UserGroupInformation.java
/** * Create a proxy user using username of the effective user and the ugi of the real user. * * @param user//w ww . j av a 2s.c o m * @param realUser * * @return proxyUser ugi */ public static UserGroupInformation createProxyUser(String user, UserGroupInformation realUser) { if (user == null || user.isEmpty()) { throw new IllegalArgumentException("Null user"); } if (realUser == null) { throw new IllegalArgumentException("Null real user"); } Subject subject = new Subject(); Set<Principal> principals = subject.getPrincipals(); principals.add(new User(user)); principals.add(new RealUser(realUser)); UserGroupInformation result = new UserGroupInformation(subject); result.setAuthenticationMethod(AuthenticationMethod.PROXY); return result; }
From source file:org.apache.coyote.tomcat5.CoyoteRequest.java
/** * Set the Principal who has been authenticated for this Request. This * value is also used to calculate the value to be returned by the * <code>getRemoteUser()</code> method. * * @param principal The user Principal//from w w w .jav a2 s. co m */ public void setUserPrincipal(Principal principal) { if (System.getSecurityManager() != null) { HttpSession session = getSession(false); if ((subject != null) && (!subject.getPrincipals().contains(principal))) { subject.getPrincipals().add(principal); } else if (session != null && session.getAttribute(Globals.SUBJECT_ATTR) == null) { subject = new Subject(); subject.getPrincipals().add(principal); } if (session != null) { session.setAttribute(Globals.SUBJECT_ATTR, subject); } } this.userPrincipal = principal; }
From source file:com.dtolabs.rundeck.core.cli.acl.AclTool.java
private Subject makeSubject(final String argUser1user, final Collection<String> groupsList1) { Subject t = new Subject(); String user = argUser1user != null ? argUser1user : "user"; t.getPrincipals().add(new Username(user)); if (null != groupsList1) { for (String s : groupsList1) { t.getPrincipals().add(new Group(s)); }/* w ww. jav a 2 s. co m*/ } return t; }
From source file:org.apache.jackrabbit.core.RepositoryImpl.java
/** * {@inheritDoc}//from w w w .ja va 2 s . com */ public Session login(Credentials credentials, String workspaceName) throws LoginException, NoSuchWorkspaceException, RepositoryException { try { shutdownLock.readLock().acquire(); } catch (InterruptedException e) { throw new RepositoryException("Login lock could not be acquired", e); } try { // check sanity of this instance sanityCheck(); if (workspaceName == null) { workspaceName = repConfig.getDefaultWorkspaceName(); } // check if workspace exists (will throw NoSuchWorkspaceException if not) getWorkspaceInfo(workspaceName); if (credentials == null) { // try to obtain the identity of the already authenticated // subject from access control context Session session = extendAuthentication(workspaceName); if (session != null) { // successful extended authentication return session; } else { log.debug( "Attempt to login without Credentials and Subject -> try login with null credentials."); } } // not preauthenticated -> try login with credentials AuthContext authCtx = getSecurityManager().getAuthContext(credentials, new Subject()); authCtx.login(); // create session return createSession(authCtx, workspaceName); } catch (SecurityException se) { throw new LoginException("Unable to access authentication information", se); } catch (javax.security.auth.login.LoginException le) { throw new LoginException(le.getMessage(), le); } catch (AccessDeniedException ade) { // authenticated subject is not authorized for the specified workspace throw new LoginException("Workspace access denied", ade); } finally { shutdownLock.readLock().release(); } }
From source file:org.apache.jackrabbit.core.RepositoryImpl.java
/** * {@inheritDoc}//w w w .j a v a 2 s.c om */ public Session login(Credentials credentials, String workspaceName) throws LoginException, NoSuchWorkspaceException, RepositoryException { try { shutdownLock.readLock().acquire(); } catch (InterruptedException e) { throw new RepositoryException("Login lock could not be acquired", e); } try { // check sanity of this instance sanityCheck(); if (workspaceName == null) { workspaceName = repConfig.getDefaultWorkspaceName(); } // check if workspace exists (will throw NoSuchWorkspaceException if not) getWorkspaceInfo(workspaceName); if (credentials == null) { // try to obtain the identity of the already authenticated // subject from access control context Session session = extendAuthentication(workspaceName); if (session != null) { // successful extended authentication return session; } else { log.debug( "Attempt to login without Credentials and Subject -> try login with null credentials."); } } // not preauthenticated -> try login with credentials AuthContext authCtx = context.getSecurityManager().getAuthContext(credentials, new Subject(), workspaceName); authCtx.login(); // create session, and add SimpleCredentials attributes (JCR-1932) SessionImpl session = createSession(authCtx, workspaceName); if (credentials instanceof SimpleCredentials) { SimpleCredentials sc = (SimpleCredentials) credentials; for (String name : sc.getAttributeNames()) { if (!TokenBasedAuthentication.isMandatoryAttribute(name)) { session.setAttribute(name, sc.getAttribute(name)); } } } Set<TokenCredentials> tokenCreds = session.getSubject().getPublicCredentials(TokenCredentials.class); if (!tokenCreds.isEmpty()) { TokenCredentials tc = tokenCreds.iterator().next(); for (String name : tc.getAttributeNames()) { if (!TokenBasedAuthentication.isMandatoryAttribute(name)) { session.setAttribute(name, tc.getAttribute(name)); } } } log.debug("User {} logged in to workspace {}", session.getUserID(), workspaceName); return session; } catch (SecurityException se) { throw new LoginException("Unable to access authentication information", se); } catch (javax.security.auth.login.LoginException le) { throw new LoginException(le.getMessage(), le); } catch (AccessDeniedException ade) { // authenticated subject is not authorized for the specified workspace throw new LoginException("Workspace access denied", ade); } finally { shutdownLock.readLock().release(); } }
From source file:org.springframework.beans.factory.DefaultListableBeanFactoryTests.java
@SuppressWarnings("unchecked") @Test/*from www . j a v a2 s .c o m*/ public void testInitSecurityAwarePrototypeBean() { final DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); RootBeanDefinition bd = new RootBeanDefinition(TestSecuredBean.class); bd.setScope(ConfigurableBeanFactory.SCOPE_PROTOTYPE); bd.setInitMethodName("init"); lbf.registerBeanDefinition("test", bd); final Subject subject = new Subject(); subject.getPrincipals().add(new TestPrincipal("user1")); TestSecuredBean bean = (TestSecuredBean) Subject.doAsPrivileged(subject, new PrivilegedAction() { @Override public Object run() { return lbf.getBean("test"); } }, null); assertNotNull(bean); assertEquals("user1", bean.getUserName()); }