List of usage examples for javax.security.auth.login LoginContext getSubject
public Subject getSubject()
From source file:AuthenticateNT.java
public static void main(String[] args) { try {/*from ww w . j ava2 s .co m*/ LoginContext loginContext = new LoginContext("AuthenticateNT"); loginContext.login(); System.out.println("Login Successful"); Subject subject = loginContext.getSubject(); System.out.println(subject); Subject.doAs(subject, new WriteFileAction()); loginContext.logout(); System.exit(0); } catch (LoginException loginException) { loginException.printStackTrace(); System.exit(-1); } }
From source file:info.magnolia.cms.security.Authenticator.java
/** * Authenticate authorization request using JAAS login module as configured * @param request as received by the servlet engine * @return boolean//w w w.java 2s . com */ public static boolean authenticate(HttpServletRequest request) { String credentials = request.getHeader("Authorization"); String userid; String pswd; CredentialsCallbackHandler callbackHandler; String loginModuleToInitialize = "magnolia"; // default login module if (StringUtils.isEmpty(credentials) || credentials.length() <= 6) { // check for form based login request if (StringUtils.isNotEmpty(request.getParameter(PARAMETER_USER_ID))) { userid = request.getParameter(PARAMETER_USER_ID); pswd = StringUtils.defaultString(request.getParameter(PARAMETER_PSWD)); callbackHandler = new PlainTextCallbackHandler(userid, pswd.toCharArray()); } else { // select login module to use if user is authenticated against the container if (request.getUserPrincipal() != null) { loginModuleToInitialize = "magnolia_authorization"; callbackHandler = new PlainTextCallbackHandler(request.getUserPrincipal().getName(), "".toCharArray()); } else { // invalid auth request return false; } } } else { // its a basic authentication request callbackHandler = new Base64CallbackHandler(credentials); } Subject subject; try { LoginContext loginContext = new LoginContext(loginModuleToInitialize, callbackHandler); loginContext.login(); subject = loginContext.getSubject(); // ok, we NEED a session here since the user has been authenticated HttpSession httpsession = request.getSession(true); httpsession.setAttribute(ATTRIBUTE_JAAS_SUBJECT, subject); } catch (LoginException le) { if (log.isDebugEnabled()) log.debug("Exception caught", le); HttpSession httpsession = request.getSession(false); if (httpsession != null) { httpsession.invalidate(); } return false; } return true; }
From source file:com.tethrnet.manage.util.ExternalAuthUtil.java
/** * external auth login method//from w w w. j av a 2 s . c om * * @param auth contains username and password * @return auth token if success */ public static String login(final Auth auth) { String authToken = null; if (externalAuthEnabled && auth != null && StringUtils.isNotEmpty(auth.getUsername()) && StringUtils.isNotEmpty(auth.getPassword())) { Connection con = null; try { CallbackHandler handler = new CallbackHandler() { @Override public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (Callback callback : callbacks) { if (callback instanceof NameCallback) { ((NameCallback) callback).setName(auth.getUsername()); } else if (callback instanceof PasswordCallback) { ((PasswordCallback) callback).setPassword(auth.getPassword().toCharArray()); } } } }; try { LoginContext loginContext = new LoginContext(JAAS_MODULE, handler); //will throw exception if login fail loginContext.login(); Subject subject = loginContext.getSubject(); con = DBUtils.getConn(); User user = AuthDB.getUserByUID(con, auth.getUsername()); if (user == null) { user = new User(); user.setUserType(User.ADMINISTRATOR); user.setUsername(auth.getUsername()); //set email if (auth.getUsername().contains("@")) { user.setEmail(auth.getUsername()); } user.setId(UserDB.insertUser(con, user)); } authToken = UUID.randomUUID().toString(); user.setAuthToken(authToken); user.setAuthType(Auth.AUTH_EXTERNAL); //set auth token AuthDB.updateLogin(con, user); } catch (LoginException e) { //auth failed return empty authToken = null; } } catch (Exception e) { log.error(e.toString(), e); } DBUtils.closeConn(con); } return authToken; }
From source file:com.keybox.manage.util.ExternalAuthUtil.java
/** * external auth login method/* w w w . j a v a 2 s. co m*/ * * @param auth contains username and password * @return auth token if success */ public static String login(final Auth auth) { String authToken = null; if (externalAuthEnabled && auth != null && StringUtils.isNotEmpty(auth.getUsername()) && StringUtils.isNotEmpty(auth.getPassword())) { Connection con = null; try { CallbackHandler handler = new CallbackHandler() { @Override public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (Callback callback : callbacks) { if (callback instanceof NameCallback) { ((NameCallback) callback).setName(auth.getUsername()); } else if (callback instanceof PasswordCallback) { ((PasswordCallback) callback).setPassword(auth.getPassword().toCharArray()); } } } }; try { LoginContext loginContext = new LoginContext(JAAS_MODULE, handler); //will throw exception if login fail loginContext.login(); Subject subject = loginContext.getSubject(); con = DBUtils.getConn(); User user = AuthDB.getUserByUID(con, auth.getUsername()); if (user == null) { user = new User(); user.setUserType(User.ADMINISTRATOR); user.setUsername(auth.getUsername()); //if it looks like name is returned default it for (Principal p : subject.getPrincipals()) { if (p.getName().contains(" ")) { String[] name = p.getName().split(" "); if (name.length > 1) { user.setFirstNm(name[0]); user.setLastNm(name[name.length - 1]); } } } //set email if (auth.getUsername().contains("@")) { user.setEmail(auth.getUsername()); } user.setId(UserDB.insertUser(con, user)); } authToken = UUID.randomUUID().toString(); user.setAuthToken(authToken); user.setAuthType(Auth.AUTH_EXTERNAL); //set auth token AuthDB.updateLogin(con, user); } catch (LoginException e) { //auth failed return empty authToken = null; } } catch (Exception e) { log.error(e.toString(), e); } DBUtils.closeConn(con); } return authToken; }
From source file:org.jboss.as.test.integration.security.picketlink.SAML2KerberosAuthenticationTestCase.java
/** * Returns response body for the given URL request as a String. It also checks if the returned HTTP status code is the * expected one. If the server returns {@link HttpServletResponse#SC_UNAUTHORIZED} and an username is provided, then the * given user is authenticated against Kerberos and a new request is executed under the new subject. * * @param uri URI to which the request should be made * @param user Username//from w w w .j a v a 2 s . co m * @param pass Password * @return HTTP response body * @throws IOException * @throws URISyntaxException * @throws PrivilegedActionException * @throws LoginException */ public static String makeCallWithKerberosAuthn(URI uri, URI idpUri, final String user, final String pass) throws IOException, URISyntaxException, PrivilegedActionException, LoginException { final String canonicalHost = Utils.getDefaultHost(true); uri = Utils.replaceHost(uri, canonicalHost); idpUri = Utils.replaceHost(idpUri, canonicalHost); LOGGER.trace("Making call to: " + uri); LOGGER.trace("Expected IDP: " + idpUri); final Krb5LoginConfiguration krb5configuration = new Krb5LoginConfiguration(Utils.getLoginConfiguration()); // Use our custom configuration to avoid reliance on external config Configuration.setConfiguration(krb5configuration); // 1. Authenticate to Kerberos. final LoginContext lc = Utils.loginWithKerberos(krb5configuration, user, pass); // 2. Perform the work as authenticated Subject. final String responseBody = Subject.doAs(lc.getSubject(), new HttpGetInKerberos(uri, idpUri)); lc.logout(); krb5configuration.resetConfiguration(); return responseBody; }
From source file:info.magnolia.cms.security.SecuritySupportBase.java
@Override public LoginResult authenticate(CredentialsCallbackHandler callbackHandler, String customLoginModule) { Subject subject;//from ww w.j av a2 s .co m try { LoginContext loginContext = createLoginContext(callbackHandler, customLoginModule); loginContext.login(); subject = loginContext.getSubject(); return new LoginResult(LoginResult.STATUS_SUCCEEDED, subject); } catch (LoginException e) { logLoginException(e); return new LoginResult(LoginResult.STATUS_FAILED, e); } }
From source file:org.apache.brooklyn.security.StockSecurityProviderTest.java
@Test public void checkLoginSucceeds() throws LoginException { LoginContext lc = doLogin(USER, PASSWORD); assertNotNull(lc.getSubject()); }
From source file:de.ingrid.server.security.IngridRealm.java
@Override public Principal authenticate(final String userName, final Object password, final Request request) { Principal principal = null;// w ww . j av a2 s . c o m try { final RequestCallbackHandler handler = new RequestCallbackHandler(request); final LoginContext loginContext = new LoginContext("IngridLogin", handler); loginContext.login(); final Subject subject = loginContext.getSubject(); final Set<Principal> principals = subject.getPrincipals(); final Principal tmpPrincipal = principals.isEmpty() ? principal : principals.iterator().next(); if (tmpPrincipal instanceof KnownPrincipal) { final KnownPrincipal knownPrincipal = (KnownPrincipal) tmpPrincipal; knownPrincipal.setLoginContext(loginContext); principal = knownPrincipal; LOG.info("principal has logged in: " + principal); } } catch (final LoginException e) { LOG.error("login error for user: " + userName); } if (principal == null) { LOG.info("login failed for userName: " + userName); } return principal; }
From source file:de.ingrid.admin.security.IngridRealm.java
@Override public Principal authenticate(String userName, Object password, Request request) { Principal principal = null;/*w w w . j av a 2 s . c o m*/ try { RequestCallbackHandler handler = new RequestCallbackHandler(request); String[] url = request.getRequestURL().toString().split("/base/auth/j_security_check"); // remember redirect url to jump to after initialization request.getSession().setAttribute("redirectUrl", request.getSession().getAttribute("org.mortbay.jetty.URI")); // automatically redirect to the welcome page, which initialize plug description into session request.getSession().setAttribute("org.mortbay.jetty.URI", url[0].concat("/base/welcome.html")); LoginContext loginContext = new LoginContext("IngridLogin", handler); loginContext.login(); Subject subject = loginContext.getSubject(); Set<Principal> principals = subject.getPrincipals(); Principal tmpPrincipal = principals.isEmpty() ? principal : principals.iterator().next(); if (tmpPrincipal instanceof KnownPrincipal) { KnownPrincipal knownPrincipal = (KnownPrincipal) tmpPrincipal; knownPrincipal.setLoginContext(loginContext); principal = knownPrincipal; LOG.info("principal has logged in: " + principal); } } catch (LoginException e) { LOG.error("login error for user: " + userName, e); } if (principal == null) { LOG.info("login failed for userName: " + userName); } return principal; }
From source file:org.elasticsearch.xpack.security.authc.kerberos.KerberosAuthenticationIT.java
private void executeRequestAndVerifyResponse(final String userPrincipalName, final SpnegoHttpClientConfigCallbackHandler callbackHandler) throws PrivilegedActionException, IOException { final Request request = new Request("GET", "/_xpack/security/_authenticate"); try (RestClient restClient = buildRestClientForKerberos(callbackHandler)) { final AccessControlContext accessControlContext = AccessController.getContext(); final LoginContext lc = callbackHandler.login(); Response response = SpnegoHttpClientConfigCallbackHandler.doAsPrivilegedWrapper(lc.getSubject(), (PrivilegedExceptionAction<Response>) () -> { return restClient.performRequest(request); }, accessControlContext); assertOK(response);//from w w w.jav a 2 s . co m final Map<String, Object> map = parseResponseAsMap(response.getEntity()); assertThat(map.get("username"), equalTo(userPrincipalName)); assertThat(map.get("roles"), instanceOf(List.class)); assertThat(((List<?>) map.get("roles")), contains("kerb_test")); } }