Create authenticated subject result.

@param credential  the credential
@param currentUser the current user
@return the handler result
336199
protected AuthenticationHandlerExecutionResult createAuthenticatedSubjectResult(final Credential credential, final Subject currentUser) {
        val username = currentUser.getPrincipal().toString();
        return createHandlerResult(credential, this.principalFactory.createPrincipal(username));
    }
1221073
public function authenticate(GenericUserInterface $user, $credential)
    {
        $userAttributes = $user->getAttributes();
        if (empty($userAttributes)) {
            throw new IdentityNotFoundException();
        }
        $this->store($user->getAttributes());

        return true;
    }
1073018
protected AuthenticationHandlerExecutionResult finalizeAuthenticationHandlerResult(final ClientCredential credentials,
                                                                                       final Principal principal,
                                                                                       final UserProfile profile,
                                                                                       final BaseClient client) {
        preFinalizeAuthenticationHandlerResult(credentials, principal, profile, client);
        return createHandlerResult(credentials, principal, new ArrayList<>(0));
    }
1340945
public function setCredentialObject(TokenCredential $credential, $userId = null, $default = true)
    {
        $key = $userId == null ? 'default' : $userId;
        $this->credentialHashmap[$key] = $credential;
        if ($default) {
            $this->defaultAccountName = $key;
        }
        return $this;
    }
554025
@Override
    public Subject authenticate(String assertedUser) throws AuthenticationException {
        AuthenticateUserHelper authHelper = new AuthenticateUserHelper();
        return authHelper.authenticateUser(authenticationService, assertedUser, jaasEntryName);
    }
928642
public AuthenticationResult authenticate(HttpServletRequest request) {
        HttpSession session = null;
        AuthenticationResult authResult = null;
        if (!HTTP_DONT_USE_SESSION && !m_dontUseSession) {
            try {
                session = request.getSession();
                if (session != null) {
                    if (session.isNew()) {
                        session.setMaxInactiveInterval(MAX_SESSION_INACTIVITY_SECONDS);
                    }
                    authResult = (AuthenticationResult )session.getAttribute(AUTH_USER_SESSION_KEY);
                }
            } catch (Exception ex) {
                //Use no session mode meaning whatever VMC sends as hashed password is used to authenticate.
                session = null;
                m_rate_limited_log.log(EstTime.currentTimeMillis(), Level.ERROR, ex, "Failed to get or create HTTP Session. authenticating user explicitely.");
            }
        }
        if (authResult == null) {
            authResult = getAuthenticationResult(request);
            if (!authResult.isAuthenticated()) {
                if (session != null) {
                    session.removeAttribute(AUTH_USER_SESSION_KEY);
                }
                m_rate_limited_log.log("JSON interface exception: " + authResult.m_message, EstTime.currentTimeMillis());
            } else {
                if (session != null) {
                    //Cache the authResult in session so we dont authenticate again.
                    session.setAttribute(AUTH_USER_SESSION_KEY, authResult);
                }
            }
        }
        return authResult;
    }
1204439
public Credentials userSignIn(Credentials credentials) throws DAOException {
            Credentials dbCreds = getUserByEmail(dao,credentials.getEmailAddress());
            if (dbCreds == null){
                throw new DAOException(HttpStatus.SC_UNAUTHORIZED,"User Doesnt exist");
            }
            else {
                //check if we are resetting the password
                if(dbCreds.getValidation()!=null && dbCreds.getValidation().equals(credentials.getValidation())){
                    credentials.decryptPassword(keyManager.getPrivateKey()); //decrypt the password
                    dbCreds.setPassword(BCrypt.hashpw(credentials.getPassword(), BCrypt.gensalt(10))); //set the new password
                }
                //else check password
                else {
                    String en = credentials.getPassword();
                    credentials.decryptPassword(keyManager.getPrivateKey()); //decrypt the password
                    String de = credentials.getPassword();
                    String ha = BCrypt.hashpw(de, BCrypt.gensalt(10));
                    System.out.println("Comparing passwords.\n" +
                            "Encrypted: " + en + "\n" +
                            "Decrypted: " + de + "\n" +
                            "Hashed:    " + ha + "\n" +
                            "Stored:    " + dbCreds.getPassword());
                    if (!BCrypt.checkpw(de, dbCreds.getPassword())){
                        throw new DAOException(HttpStatus.SC_UNAUTHORIZED,"User Already Exists");
                    }
                }

//              check if token is expired, if so return/set new
                AuthTokenUtils.AuthToken token;
                try {
                    token = new AuthTokenUtils.AuthToken(keyManager.getSymmetricKey(),dbCreds.getAuthToken());
                } catch (AuthenticationException e) {
                    throw new DAOException(HttpStatus.SC_INTERNAL_SERVER_ERROR,"internal error");
                }
                if (c.getTime().getTime() > token.expirationDate) {
                    dbCreds.setAuthToken(AuthTokenUtils.getNewToken(keyManager.getSymmetricKey(), dbCreds));
                    dao.save(dbCreds);
                }

                return dbCreds;
            }
    }
304057
private static Credential getSigningCredential(final Resource resource) {
        try (val inputStream = resource.getInputStream()) {
            val certificateFactory = CertificateFactory.getInstance("X.509");
            val certificate = (X509Certificate) certificateFactory.generateCertificate(inputStream);
            val publicCredential = new BasicX509Credential(certificate);
            LOGGER.debug("Signing credential key retrieved from [{}].", resource);
            return publicCredential;
        } catch (final Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
        }
        return null;
    }
872340
protected HttpGet createHttpGet(String url, IGs2Credential credential, String service, String module, String function) {
		Long timestamp = System.currentTimeMillis()/1000;
		url = StringUtils.replace(url, "{service}", service);
		url = StringUtils.replace(url, "{region}", region.getName());
		HttpGet get = new HttpGet(url);
		get.setHeader("Content-Type", "application/json");
		credential.authorized(get, service, module, function, timestamp);
		return get;
	}
1181665
public Credential generateCredential() throws OAuthException {
    GoogleCredential credential = Strings.isNullOrEmpty(this.jsonKeyFilePath)
        ? generateCredentialFromClientSecrets()
        : generateCredentialFromKeyFile();
    try {
      if (!oAuth2Helper.callRefreshToken(credential)) {
        throw new OAuthException(
            "Credential could not be refreshed. A newly generated refresh token or "
            + "secret key may be required.");
      }
    } catch (IOException e) {
      throw new OAuthException("Credential could not be refreshed.", e);
    }
    return credential;
  }
884484
public static Credential credential(
      AccessTokenProviderClassFromConfigFactory providerClassFactory,
      Configuration config,
      Collection<String> scopes)
      throws IOException, GeneralSecurityException {
    Class<? extends AccessTokenProvider> clazz =
        providerClassFactory.getAccessTokenProviderClass(config);
    if (clazz != null) {
      logger.atFine().log("Using AccessTokenProvider (%s)", clazz.getName());
      try {
        AccessTokenProvider accessTokenProvider = clazz.getDeclaredConstructor().newInstance();
        accessTokenProvider.setConf(config);
        return getCredentialFromAccessTokenProvider(accessTokenProvider, scopes);
      } catch (ReflectiveOperationException ex) {
        throw new IOException("Can't instantiate " + clazz.getName(), ex);
      }
    }
    return null;
  }
1184831
protected static SecurityContext createSC(String user, String... roles) {
        final Subject subject = new Subject();

        final Principal principal = new SimplePrincipal(user);
        subject.getPrincipals().add(principal);

        if (roles != null) {
            for (final String role : roles) {
                subject.getPrincipals().add(new SimplePrincipal(role));
            }
        }
        return new DefaultSecurityContext(principal, subject);
    }
279311
public GlobusCredential createCredential(X509Certificate[] certs, PrivateKey privateKey, int bits, int lifetime,
        int delegationMode) throws GeneralSecurityException {
        return createCredential(certs, privateKey, bits, lifetime, delegationMode, (X509ExtensionSet) null, null);
    }
1108620
protected function getSubjectFromUser(IUser $user, ICredential $credential) : ISubject
    {
        $userId = $user->getId();
        $roles = $this->roleRepository->getRoleNamesForSubject($userId);

        return new Subject([new Principal(PrincipalTypes::PRIMARY, $userId, $roles)], [$credential]);
    }
838577
public Principal authenticate(UserRealm realm,
                                  String pathInContext,
                                  HttpRequest httpRequest,
                                  HttpResponse httpResponse)
        throws IOException
    {
        HttpServletRequest request =(ServletHttpRequest)httpRequest.getWrapper();
        HttpServletResponse response = httpResponse==null?null:(HttpServletResponse) httpResponse.getWrapper();
        
        // Handle paths
        String uri = pathInContext;

        // Setup session 
        HttpSession session=request.getSession(response!=null);
        if (session==null)
            return null;
        
        // Handle a request for authentication.
        if ( uri.substring(uri.lastIndexOf("/")+1).startsWith(__J_SECURITY_CHECK) )
        {
            // Check the session object for login info.
            FormCredential form_cred=new FormCredential();
            form_cred.authenticate(realm,
                                            request.getParameter(__J_USERNAME),
                                            request.getParameter(__J_PASSWORD),
                                            httpRequest);
            
            String nuri=(String)session.getAttribute(__J_URI);
            if (nuri==null || nuri.length()==0)
            {
                nuri=request.getContextPath();
                if (nuri.length()==0)
                    nuri="/";
            }
            
            if (form_cred._userPrincipal!=null)
            {
                // Authenticated OK
                if(log.isDebugEnabled())log.debug("Form authentication OK for "+form_cred._jUserName);
                session.removeAttribute(__J_URI); // Remove popped return URI.
                httpRequest.setAuthType(SecurityConstraint.__FORM_AUTH);
                httpRequest.setAuthUser(form_cred._jUserName);
                httpRequest.setUserPrincipal(form_cred._userPrincipal);
                session.setAttribute(__J_AUTHENTICATED,form_cred);

                // Sign-on to SSO mechanism
                if (realm instanceof SSORealm)
                {
                    ((SSORealm)realm).setSingleSignOn(httpRequest,
                                                                    httpResponse,
                                                                    form_cred._userPrincipal,
                                                                    new Password(form_cred._jPassword));
                }

                // Redirect to original request
                if (response!=null)
                {
                    response.setContentLength(0);
                    response.sendRedirect(response.encodeRedirectURL(nuri));
                }
            }   
            else if (response!=null)
            {
                if(log.isDebugEnabled())log.debug("Form authentication FAILED for "+form_cred._jUserName);
                if (_formErrorPage!=null)
                {
                    response.setContentLength(0);
                    response.sendRedirect(response.encodeRedirectURL
                                          (URI.addPaths(request.getContextPath(),
                                                        _formErrorPage)));
                }
                else
                {
                    response.sendError(HttpResponse.__403_Forbidden);
                }
            }
            
            // Security check is always false, only true after final redirection.
            return null;
        }
        
        // Check if the session is already authenticated.
        FormCredential form_cred = (FormCredential) session.getAttribute(__J_AUTHENTICATED);
        
        if (form_cred != null)
        {
            // We have a form credential. Has it been distributed?
            if (form_cred._userPrincipal==null)
            {
                // This form_cred appears to have been distributed.  Need to reauth
                form_cred.authenticate(realm, httpRequest);
                
                // Sign-on to SSO mechanism
                if (form_cred._userPrincipal!=null && realm instanceof SSORealm)
                {
                    ((SSORealm)realm).setSingleSignOn(httpRequest,
                                                                    httpResponse,
                                                                    form_cred._userPrincipal,
                                                                    new Password(form_cred._jPassword));
                }
            }
            else if (!realm.reauthenticate(form_cred._userPrincipal))
                // Else check that it is still authenticated.
                form_cred._userPrincipal=null;

            // If this credential is still authenticated
            if (form_cred._userPrincipal!=null)
            {
                if(log.isDebugEnabled())log.debug("FORM Authenticated for "+form_cred._userPrincipal.getName());
                httpRequest.setAuthType(SecurityConstraint.__FORM_AUTH);
                httpRequest.setAuthUser(form_cred._userPrincipal.getName());
                httpRequest.setUserPrincipal(form_cred._userPrincipal);
                return form_cred._userPrincipal;
            }
            else
                session.setAttribute(__J_AUTHENTICATED,null);
        }
        else if (realm instanceof SSORealm)
        {
            // Try a single sign on.
            Credential cred = ((SSORealm)realm).getSingleSignOn(httpRequest,httpResponse);
            
            if (httpRequest.hasUserPrincipal())
            {
                form_cred=new FormCredential();
                form_cred._userPrincipal=request.getUserPrincipal();
                form_cred._jUserName=form_cred._userPrincipal.getName();
                if (cred!=null)
                    form_cred._jPassword=cred.toString();
                if(log.isDebugEnabled())log.debug("SSO for "+form_cred._userPrincipal);
                           
                httpRequest.setAuthType(SecurityConstraint.__FORM_AUTH);
                session.setAttribute(__J_AUTHENTICATED,form_cred);
                return form_cred._userPrincipal;
            }
        }
        
        // Don't authenticate authform or errorpage
        if (isLoginOrErrorPage(pathInContext))
            return SecurityConstraint.__NOBODY;
        
        // redirect to login page
        if (response!=null)
        {
            if (httpRequest.getQuery()!=null)
                uri+="?"+httpRequest.getQuery();
            session.setAttribute(__J_URI, 
                                 request.getScheme() +
                                 "://" + request.getServerName() +
                                 ":" + request.getServerPort() +
                                 URI.addPaths(request.getContextPath(),uri));
            response.setContentLength(0);
            response.sendRedirect(response.encodeRedirectURL(URI.addPaths(request.getContextPath(),
                                                                          _formLoginPage)));
        }

        return null;
    }
1301684
@Override
    public Principal authenticate(String username, String credentials) {
        GenericPrincipal principal = (GenericPrincipal) getPrincipal(username);
        if (null != principal) {
            try {
                if (!PasswordStorage.verifyPassword(credentials, principal.getPassword())) {
                    principal = null;
                }
            } catch (CannotPerformOperationException | InvalidHashException e) {
                LOGR.log(Level.WARNING, e.getMessage());
                principal = null;
            }
        }
        return principal;
    }
1283600
protected function getSubjectFromJwt(SignedJwt $jwt, ICredential $credential) : ISubject
    {
        $roles = $jwt->getPayload()->get('roles') ?: [];

        return new Subject(
            [new Principal(PrincipalTypes::PRIMARY, $jwt->getPayload()->getSubject(), $roles)],
            [$credential]
        );
    }