does a lookup for a user record using 'user' as key. Compares pw with 'pwd' of user record if found
if user denotes a vaild old session id and pwd == 'SESSION_ID', a session is created from a previous authentication

@param pw
@param jwt
@return
187365
protected IPromise<BasicAuthenticationResult> getCredentials(String user, String pw, String jwt) {
        Promise p = new Promise();
        if ( SESSIONID_SPECIAL_STRING.equals(pw) ) {
            sessionStorage.getUserFromSessionId(user).then( (r,e) -> {
                if ( r != null ) {
                    sessionStorage.getUser(r).then( (rec,err) -> {
                        if ( rec != null )
                            getCredentials(rec.getKey(),rec.getString("pwd"), null ).then(p);
                        else
                            p.reject("unknown user");
                    });
                } else {
                    p.reject("authentication failed");
                }
            });
        } else {
            sessionStorage.getUser(user).then((rec, err) -> {
                if (rec == null) {
                    p.reject("wrong user or password");
                } else {
                    if (pw.equals(rec.getString("pwd"))) {
                        if (!rec.getBool("verified")) {
                            // e.g. email verification etc.
                            p.reject("account not verified");
                        } else
                            p.resolve(new BasicAuthenticationResult().userName(rec.getKey()));
                    }
                }
            });
        }
        return p;
    }
1333780
@Override
    public JSONObject get(String path, Map<String,String> headers) throws ServiceException, JSONException {
        // we trust this header value because only MDW can set it
        String authUser = (String)headers.get(Listener.AUTHENTICATED_USER_HEADER);
        try {
            if (authUser == null)
                throw new ServiceException("Missing parameter: " + Listener.AUTHENTICATED_USER_HEADER);
            UserServices userServices = ServiceLocator.getUserServices();
            User userVO = userServices.getUser(authUser);
            if (userVO == null)
                throw new ServiceException(HTTP_404_NOT_FOUND, "User not found: " + authUser);
            return userVO.getJsonWithRoles();
        }
        catch (DataAccessException ex) {
                throw new ServiceException(ex.getCode(), ex.getMessage(), ex);
        }
        catch (Exception ex) {
            throw new ServiceException("Error getting authenticated user: " + authUser, ex);
        }
    }
1199998
@Override
    public synchronized UserTransaction getUserTransaction()
    {
        // d367572.1 start
        if (state == PRE_CREATE)
        {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                Tr.debug(tc, "Incorrect state: " + getStateName(state));
            throw new IllegalStateException(getStateName(state));
        }
        // d367572.1 end

        return UserTransactionWrapper.INSTANCE; // d631349

    }
201312
public static String generateAccessToken(String username) {
		String accessToken = Jwts.builder().setIssuer(JWTUtils.ISSUER)
				.setIssuedAt(new Date(System.currentTimeMillis()))
    	        .setExpiration(new Date(System.currentTimeMillis() + JWTUtils.ACCESS_TOKEN_EXPIRATION_MILLIS))
    	        .setSubject(username)
    	        .claim("type", TokenType.ACCESS)
    	        .signWith(SignatureAlgorithm.HS256, JWTUtils.SECRET)
    	        .compact();
		
		return accessToken;
	}
745983
static String getAccessTokenForUserId(String userId) {
        if (userId == null && getUserId() == null
                || userId != null && userId.equals(getUserId())) {
            return getAccessToken();
        } else {
            JSONObject usersArchive = getJSONObject(PER_USER_ARCHIVE_PREF_NAME);
            if (usersArchive == null) usersArchive = new JSONObject();
            JSONObject userArchive = usersArchive.optJSONObject(userId == null ? "" : userId);
            if (userArchive == null) userArchive = new JSONObject();
            return JSONUtil.optString(userArchive, ACCESS_TOKEN_PREF_NAME);
        }
    }
1336112
public int auth_getUserId(String authToken)
    throws FacebookException, IOException {
    /*
     * Get the session information if we don't have it; this will populate
	   * the user ID as well.
	   */
    if (null == this._sessionKey)
      auth_getSession(authToken);
    return this._userId;
  }
242329
def verify_fresh_jwt_in_request():
    
    if request.method not in config.exempt_methods:
        jwt_data = _decode_jwt_from_request(request_type='access')
        ctx_stack.top.jwt = jwt_data
        fresh = jwt_data['fresh']
        if isinstance(fresh, bool):
            if not fresh:
                raise FreshTokenRequired('Fresh token required')
        else:
            now = timegm(datetime.utcnow().utctimetuple())
            if fresh < now:
                raise FreshTokenRequired('Fresh token required')
        verify_token_claims(jwt_data)
        _load_user(jwt_data[config.identity_claim_key])
1017754
def verify_token(token)
        logger.debug("Verifying token: #{token}")

        # First get the payload of the token. This will also verify whether
        # or not the token is welformed.
        payload = get_token_payload(token)

        # Next, the payload should define user UUID and session UUID.
        user_uuid = payload["user_uuid"]
        session_uuid = payload["session_uuid"]
        if user_uuid.nil? || session_uuid.nil?
          logger.error("User or session is not specified")
          raise UNAUTHORIZED_ERROR, "Invalid token"
        end
        logger.debug("Token well defined: #{token}")

        # But, the user UUID and session UUID better be valid too. That is,
        # they must be real user and session, and the session must belong to
        # the user.
        auth_user = User.find_by_uuid(user_uuid)
        if auth_user.nil?
          # :nocov:
          logger.error("Specified user doesn't exist #{user_uuid}")
          raise UNAUTHORIZED_ERROR, "Invalid token"
          # :nocov:
        end
        auth_session = Session.find_by_uuid(session_uuid)
        if auth_session.nil? || auth_session.user != auth_user
          logger.error("Specified session doesn't exist #{session_uuid}")
          raise UNAUTHORIZED_ERROR, "Invalid token"
        end

        # Finally, decode the token using the secret. Also check expiration
        # here too.
        JWT.decode token, auth_session.secret, true
        logger.debug("Token well formatted and verified. Set cache.")

        # Return the corresponding session
        return auth_session

      rescue JWT::DecodeError => e
        logger.error(e.message)
        raise UNAUTHORIZED_ERROR, "Invalid token"
      end
58172
def verify_jwt_in_request():
    
    if request.method not in config.exempt_methods:
        jwt_data = _decode_jwt_from_request(request_type='access')
        ctx_stack.top.jwt = jwt_data
        verify_token_claims(jwt_data)
        _load_user(jwt_data[config.identity_claim_key])
1048536
public User login(Credentials credentials) throws AuthenticationException {
		//if a user wants to log in, we assume he's not surprised if
		//  his session was expired (hence the 'true')
		User user = getSession(true).login(credentials);
		entryPoint.onSessionUpdate(this, session);
		return user;
	}
746915
public Hash deleteUser(int userId) throws AuthyException {
        final Response response = this.post(DELETE_USER_PATH + Integer.toString(userId), null);
        return instanceFromJson(response.getStatus(), response.getBody());
    }
336199
protected AuthenticationHandlerExecutionResult createAuthenticatedSubjectResult(final Credential credential, final Subject currentUser) {
        val username = currentUser.getPrincipal().toString();
        return createHandlerResult(credential, this.principalFactory.createPrincipal(username));
    }
507534
static ClientAssertion buildJwt(final AsymmetricKeyCredential credential,
            final String jwtAudience) throws AuthenticationException {
        if (credential == null) {
            throw new IllegalArgumentException("credential is null");
        }

        final long time = System.currentTimeMillis();

        final JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
                .audience(Collections.singletonList(jwtAudience))
                .issuer(credential.getClientId())
                .jwtID(UUID.randomUUID().toString())
                .notBeforeTime(new Date(time))
                .expirationTime(new Date(time
                                + AuthenticationConstants.AAD_JWT_TOKEN_LIFETIME_SECONDS
                                * 1000))
                .subject(credential.getClientId())
                .build();

        SignedJWT jwt;
        try {
            JWSHeader.Builder builder = new Builder(JWSAlgorithm.RS256);
            List<Base64> certs = new ArrayList<Base64>();
            certs.add(new Base64(credential.getPublicCertificate()));
            builder.x509CertChain(certs);
            builder.x509CertThumbprint(new Base64URL(credential
                    .getPublicCertificateHash()));
            jwt = new SignedJWT(builder.build(), claimsSet);
            final RSASSASigner signer = new RSASSASigner(credential.getKey());

            jwt.sign(signer);
        }
        catch (final Exception e) {
            throw new AuthenticationException(e);
        }

        return new ClientAssertion(jwt.serialize());
    }
1284545
public function user()
    {
        // If we've already retrieved the user for the current request we can just
        // return it back immediately. We do not want to fetch the user data on
        // every call to this method because that would be tremendously slow.
        if (! is_null($this->user)) {
            return $this->user;
        }

        $user = null;

        // If a user ID was provided in the JWT, then
        // we should attempt to fetch their profile.
        if (! empty($this->id())) {
            $user = $this->provider->retrieveById($this->id());
        }

        return $this->user = $user;
    }
51391
public String generateJwt() throws NexmoUnacceptableAuthException {
        JWTAuthMethod authMethod = this.httpWrapper.getAuthCollection().getAuth(JWTAuthMethod.class);
        return authMethod.constructToken(System.currentTimeMillis() / 1000L, JWTAuthMethod.constructJTI());
    }
1161383
public Object setUserData(String key, Object data, UserDataHandler handler) {
	// dynamic load to support jre 1.4 and 1.5
	try {
	    Method m = node.getClass().getMethod("setUserData", new Class[] { key.getClass(), data.getClass(), handler.getClass() });
	    return m.invoke(node, new Object[] { key, data, handler });
	}
	catch (Exception e) {
	    throw new PageRuntimeException(Caster.toPageException(e));
	}
    }
144705
def get_user_by_action_token(action, token):
    
    data = utils.unsign_url_safe(token,
                                 secret_key=get_jwt_secret(),
                                 salt=action)
    if data is None:
        raise exceptions.AuthError("Invalid Token")
    return get_user_by_id(int(data))