List of usage examples for javax.security.auth.login LoginContext LoginContext
public LoginContext(String name, CallbackHandler callbackHandler) throws LoginException
From source file:br.mdarte.exemplo.academico.accessControl.ControleAcessoImpl.java
public Subject login(String login, String senha) { LoginContext loginContext = null; try {// w w w . ja v a 2 s . co m CallbackHandler handler = new LoginCallbackHandler(login, senha); loginContext = new LoginContext("sistemaacademico", handler); loginContext.login(); Subject subject = loginContext.getSubject(); accessControl.SecurityHolder.setSubject(subject); PrincipalImpl principal = getCallerPrincipal(subject); principal.setNomeProjeto("sistemaacademico"); return subject; } catch (LoginException e) { System.err.println(e.getMessage()); return null; } }
From source file:net.java.jaspicoil.SimpleBasicServerAuthModule.java
/** * Authenticate a received service request. * <p/>//from ww w. j a v a 2s . co m * This method is called to transform the mechanism-specific request message * acquired by calling getRequestMessage (on messageInfo) into the validated * application message to be returned to the message processing runtime. If * the received message is a (mechanism-specific) meta-message, the method * implementation must attempt to transform the meta-message into a * corresponding mechanism-specific response message, or to the validated * application request message. The runtime will bind a validated * application message into the the corresponding service invocation. * <p> * This method conveys the outcome of its message processing either by * returning an AuthStatus value or by throwing an AuthException. * <p/> * From a performance point of view this method will be called twice for * each resource with a security constraint on it. Resources with no * security constraint do not result in a call to this method. * * @param messageInfo * A contextual object that encapsulates the client request and * server response objects, and that may be used to save state * across a sequence of calls made to the methods of this * interface for the purpose of completing a secure message * exchange. * @param clientSubject * A Subject that represents the source of the service request. * It is used by the method implementation to store Principals * and credentials validated in the request. * @param serviceSubject * A Subject that represents the recipient of the service * request, or null. It may be used by the method implementation * as the source of Principals or credentials to be used to * validate the request. If the Subject is not null, the method * implementation may add additional Principals or credentials * (pertaining to the recipient of the service request) to the * Subject. * @return An AuthStatus object representing the completion status of the * processing performed by the method. The AuthStatus values that * may be returned by this method are defined as follows: * <p/> * <ul> * <li>AuthStatus.SUCCESS when the application request message was * successfully validated. The validated request message is * available by calling getRequestMessage on messageInfo. * <p/> * <li>AuthStatus.SEND_SUCCESS to indicate that * validation/processing of the request message successfully * produced the secured application response message (in * messageInfo). The secured response message is available by * calling getResponseMessage on messageInfo. * <p/> * <li>AuthStatus.SEND_CONTINUE to indicate that message validation * is incomplete, and that a preliminary response was returned as * the response message in messageInfo. * <p/> * When this status value is returned to challenge an application * request message, the challenged request must be saved by the * authentication module such that it can be recovered when the * module's validateRequest message is called to process the request * returned for the challenge. * <p/> * <li>AuthStatus.SEND_FAILURE to indicate that message validation * failed and that an appropriate failure response message is * available by calling getResponseMessage on messageInfo. * </ul> * @throws AuthException When the message processing failed without * establishing a failure response message (in messageInfo). */ public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException { // Get the servlet context final HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage(); final HttpServletResponse response = (HttpServletResponse) messageInfo.getResponseMessage(); final String auth = request.getHeader(AUTHORIZATION_HEADER); // Test prefix for HTTP BASIC Auth if (auth != null && StringUtils.startsWithIgnoreCase(auth, "basic ")) { // We might have a valid header, so try to decode it final String data = new String(Base64.decodeBase64(auth.substring(BASIC_PREFIX_LENGTH)), UTF_8); final int splitIndex = data.indexOf(':'); if (splitIndex < 0) { return sendErrorAndAuthenticateRequest(request, response, "Wrong WWW-Authenticate header format"); } final String username = data.substring(splitIndex); final char[] password = data.substring(splitIndex + 1, data.length()).toCharArray(); // Prepare the JAAS callback to feed any LoginModule with user and password final NameCallback nameCallback = new NameCallback("username"); nameCallback.setName(username); final PasswordCallback passwordCallback = new PasswordCallback(getRealm(request), false); passwordCallback.setPassword(password); final CallbackHandler delegatedHandler = new CallbackHandler() { public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (int i = 0; i < callbacks.length; i++) { final Callback c = callbacks[i]; if (c instanceof NameCallback) { ((NameCallback) c).setName(username); } else if (c instanceof PasswordCallback) { ((PasswordCallback) c).setPassword(password); } else { throw new UnsupportedOperationException( String.format("Callback type %s (%s) is not supported yet.", c.getClass(), c)); } } } }; if (this.jaasContextName == null) { throw new UnsupportedOperationException( "No delegate JAAS context found. As per JASPIC JAAS Bridge profile, this parameter is requiered."); } try { // Create a new JAAS context with the delegated data & try to login final LoginContext context = new LoginContext(this.jaasContextName, delegatedHandler); context.login(); // Get the authenticated subject from the JAAS context Subject authenticatedSubject = context.getSubject(); final PasswordValidationCallback passwordValidationCallback = new PasswordValidationCallback( authenticatedSubject, username, password); // notify JASPIC containerr for the name, password and subject this.handler.handle(new Callback[] { passwordValidationCallback }); } catch (final LoginException ex) { // If there was any issue during the JAAS login, fail the process final AuthException aex = new AuthException( String.format("Fail to login user %s with the delegated JAAS context %s", username, this.jaasContextName)); aex.initCause(ex); } catch (final IOException e) { LOG.log(Level.WARNING, "Unable to call the handlers for name=" + nameCallback, e); } catch (final UnsupportedCallbackException e) { LOG.log(Level.WARNING, "Unable to call the handlers for name=" + nameCallback, e); } } else if (this.mandatory) { return sendErrorAndAuthenticateRequest(request, response, "AuthModule was mandatory but no valid credential was provided"); } else { LOG.info("No authentication was provided bu Basic AuthModule is not mandatory so return SUCCESS."); } return AuthStatus.SUCCESS; }
From source file:org.wso2.carbon.mediator.kerberos.KerberosMediator.java
/** * Create GSSCredential for the user.// ww w. j a v a 2s . co m * * @param callbackHandler callback handler. * @param mechanismOId Oid for the mechanism. * @return GSSCredential. * @throws LoginException * @throws PrivilegedActionException * @throws GSSException */ private GSSCredential createClientCredentials(CallbackHandler callbackHandler, final Oid mechanismOId) throws LoginException, PrivilegedActionException, GSSException { LoginContext loginContext; String loginName; if (StringUtils.isNotEmpty(getLoginContextName())) { loginName = getLoginContextName(); } else { loginName = "com.sun.security.auth.module.Krb5LoginModule"; } if (callbackHandler != null) { loginContext = new LoginContext(loginName, callbackHandler); } else { loginContext = new LoginContext(loginName); } loginContext.login(); if (log.isDebugEnabled()) { log.debug("Pre-authentication successful for with Kerberos Server."); } // Create client credentials from pre authentication with the AD final GSSName clientName = gssManager.createName(clientPrincipalValue, GSSName.NT_USER_NAME); final PrivilegedExceptionAction<GSSCredential> action = new PrivilegedExceptionAction<GSSCredential>() { public GSSCredential run() throws GSSException { return gssManager.createCredential(clientName.canonicalize(mechanismOId), GSSCredential.DEFAULT_LIFETIME, mechanismOId, GSSCredential.INITIATE_ONLY); } }; if (log.isDebugEnabled()) { Set<Principal> principals = loginContext.getSubject().getPrincipals(); String principalName = null; if (principals != null) { principalName = principals.toString(); } log.debug("Creating gss credentials as principal : " + principalName); } return Subject.doAs(loginContext.getSubject(), action); }
From source file:de.juwimm.cms.authorization.remote.AuthorizationServiceSpringImpl.java
@Override protected void handleRemoteLoginLive(String userName, String pass) throws Exception { UserHbm user;/*ww w .j a v a 2 s.c o m*/ try { user = getUserHbmDao().load(userName); } catch (Exception ex) { throw new SecurityException("Invalid Principal"); } user.setLoginDate((System.currentTimeMillis())); LoginContext lc = new LoginContext("juwimm-cms-security-domain", new CredentialCallbackHandler(userName, pass)); lc.login(); //UserLoginValue ulv = getUserHbmDao().getUserLoginValue(user); //return ulv; }
From source file:de.juwimm.cms.authorization.remote.AuthorizationServiceSpringImpl.java
@Override protected UserLoginValue handleRemoteLogin(String userName, String pass) throws Exception { UserHbm user;//from w ww . ja v a2 s. c o m try { user = getUserHbmDao().load(userName); } catch (Exception ex) { throw new SecurityException("Invalid Principal"); } user.setLoginDate((System.currentTimeMillis())); LoginContext lc = new LoginContext("juwimm-cms-security-domain", new CredentialCallbackHandler(userName, pass)); lc.login(); UserLoginValue ulv = getUserHbmDao().getUserLoginValue(user); return ulv; }
From source file:com.yoshio3.modules.AzureADServerAuthModule.java
private AuthStatus getAuthResultFromServerAndSetSession(Subject clientSubject, HttpServletRequest httpRequest, Map<String, String> params, String currentUri) { try {//from www .j av a 2s.com String fullUrl = currentUri + (httpRequest.getQueryString() != null ? "?" + httpRequest.getQueryString() : ""); AuthenticationResponse authResponse = AuthenticationResponseParser.parse(new URI(fullUrl), params); //params ?? error ???????AuthenticationErrorResponse // if there is an error key in params, return AuthenticationErrorResponse //??? AuthenticationSuccessResponse ? // if it was successful, return AuthenticationSuccessResponse //?????? // if authentication was successful if (authResponse instanceof AuthenticationSuccessResponse) { //??????? // obtain the result from the response and save it in the session AuthenticationSuccessResponse authSuccessResponse = (AuthenticationSuccessResponse) authResponse; AuthenticationResult result = getAccessToken(authSuccessResponse.getAuthorizationCode(), currentUri); AzureADUserPrincipal userPrincipal = new AzureADUserPrincipal(result); setSessionPrincipal(httpRequest, userPrincipal); //? // set the user principal String[] groups = getGroupList(userPrincipal); System.out.println(": " + Arrays.toString(groups)); AzureADCallbackHandler azureCallBackHandler = new AzureADCallbackHandler(clientSubject, httpRequest, userPrincipal); loginContext = new LoginContext(LOGIN_CONTEXT_NAME, azureCallBackHandler); loginContext.login(); Subject subject = loginContext.getSubject(); CallerPrincipalCallback callerCallBack = new CallerPrincipalCallback(clientSubject, userPrincipal); GroupPrincipalCallback groupPrincipalCallback = new GroupPrincipalCallback(clientSubject, groups); Callback[] callbacks = new Callback[] { callerCallBack, groupPrincipalCallback }; handler.handle(callbacks); return AuthStatus.SUCCESS; } else { // ????? // if authentication failed AuthenticationErrorResponse authErrorResponse = (AuthenticationErrorResponse) authResponse; CallerPrincipalCallback callerCallBack = new CallerPrincipalCallback(clientSubject, (Principal) null); GroupPrincipalCallback groupPrincipalCallback = new GroupPrincipalCallback(clientSubject, null); Callback[] callbacks = new Callback[] { callerCallBack, groupPrincipalCallback }; handler.handle(callbacks); return AuthStatus.FAILURE; } } catch (Throwable ex) { CallerPrincipalCallback callerCallBack = new CallerPrincipalCallback(clientSubject, (Principal) null); GroupPrincipalCallback groupPrincipalCallback = new GroupPrincipalCallback(clientSubject, null); Callback[] callbacks = new Callback[] { callerCallBack, groupPrincipalCallback }; try { handler.handle(callbacks); } catch (IOException | UnsupportedCallbackException ex1) { LOGGER.log(Level.SEVERE, null, ex1); } LOGGER.log(Level.SEVERE, null, ex); return AuthStatus.FAILURE; } }
From source file:com.stimulus.archiva.security.realm.ADRealm.java
protected LoginContext kereberosLogin(Config config, ADIdentity identity, String username, String password) throws ArchivaException { logger.debug("kerberosLogin()"); String domain = null;/*from www.jav a2 s . c o m*/ String uname = null; LoginContext serverLC = null; BeanCallbackHandler beanCallbackHandler = null; String kdcAddress = identity.getKDCAddress(); if (username.length() < 1) throw new ArchivaException("A service account login name must be specified.", logger); if (password.length() < 1) throw new ArchivaException("A service account login password must be specified.", logger); int at = username.lastIndexOf('@'); if (at == -1) throw new ArchivaException( "The service account login name must be in the format username@company.local.", logger); uname = username.substring(0, at).toLowerCase(Locale.ENGLISH); domain = username.substring(at + 1).toUpperCase(Locale.ENGLISH); logger.debug("kerberosLogin() {domain='" + domain + "', uname='" + username + "',kdcAddress='" + kdcAddress + "'}"); String confFile = Config.getFileSystem().getConfigurationPath() + File.separatorChar + "login.conf"; String krbFile = Config.getFileSystem().getConfigurationPath() + File.separatorChar + "krb5.conf"; beanCallbackHandler = new BeanCallbackHandler(uname, password); if (!new File(krbFile).exists()) { System.setProperty("java.security.krb5.realm", domain); System.setProperty("java.security.krb5.kdc", kdcAddress); if (logger.isDebugEnabled()) System.setProperty("sun.security.krb5.debug", "true"); } else { System.setProperty("java.security.krb5.conf", krbFile); } System.setProperty("java.security.auth.login.config", confFile); try { serverLC = new LoginContext(confName, beanCallbackHandler); serverLC.login(); } catch (Exception e) { throw new ArchivaException("failed to login using kerberos server. " + e.getMessage() + " {realm='" + domain + "',kdcAddress='" + kdcAddress + "'}", e, logger); } logger.debug("kerberosLogin() end"); return serverLC; }
From source file:it.cnr.icar.eric.client.xml.registry.ConnectionImpl.java
/** * Forces authentication to occur.// ww w . jav a 2 s .c o m ** Add to JAXR 2.0?? * * @throws JAXRException DOCUMENT ME! */ public void authenticate() throws JAXRException { // Obtain a LoginContext, needed for authentication. Tell it // to use the LoginModule implementation specified by the // entry named "Sample" in the JAAS login configuration // file and to also use the specified CallbackHandler. LoginContext lc = null; try { loginModuleMgr.createLoginConfigFile(); String applicationName = loginModuleMgr.getApplicationName(); handler = loginModuleMgr.getCallbackHandler(); lc = new LoginContext(applicationName, handler); // attempt authentication lc.login(); //Get the authenticated Subject. Subject subject = lc.getSubject(); Set<Object> privateCredentials = subject.getPrivateCredentials(); //Set credentials on JAXR Connections setCredentials(privateCredentials); log.info(JAXRResourceBundle.getInstance().getString("message.SetCredentialsOnConnection")); } catch (LoginException le) { String msg = le.getMessage(); if ((msg != null) && (!(msg.equalsIgnoreCase("Login cancelled")))) { throw new JAXRException(le); } } catch (SecurityException se) { throw new JAXRException(se); } }
From source file:com.adito.activedirectory.ActiveDirectoryUserDatabaseConfiguration.java
LoginContext createLoginContext(String username, String password) throws LoginException { if (logger.isDebugEnabled()) { logger.debug("Creating login context for " + username); }/*from w ww. j a va 2s . c o m*/ UserPasswordCallbackHandler callbackHandler = new UserPasswordCallbackHandler(); callbackHandler.setUserId(username); callbackHandler.setPassword(password); LoginContext context = new LoginContext(ActiveDirectoryUserDatabase.class.getName(), callbackHandler); context.login(); return context; }