POST /tokens

<p>Returns a newly-generated token belonging to the current login user.
178959
@Post("/tokens")
    @StatusCode(201)
    @ResponseConverter(CreateApiResponseConverter.class)
    public CompletableFuture<HttpResult<Token>> createToken(@Param("appId") String appId,
                                                                    @Param("isAdmin") boolean isAdmin,
                                                                    Author author, User loginUser) {
        checkArgument(!isAdmin || loginUser.isAdmin(),
                      "Only administrators are allowed to create an admin-level token.");
        return mds.createToken(author, appId, isAdmin)
                  .thenCompose(unused -> mds.findTokenByAppId(appId))
                  .thenApply(token -> {
                      final HttpHeaders headers = HttpHeaders.of(HttpStatus.CREATED)
                                                             .add(HttpHeaderNames.LOCATION, "/tokens/" + appId);
                      return HttpResult.of(headers, token);
                  });
    }
1273743
public function tokenResetAction()
    {
        $token = $this->get('request_stack')->getCurrentRequest()->get('token');
        if (!$token) {
            return $this->render('FOMUserBundle:Login:error-notoken.html.twig');
        }

        $user = $this->getDoctrine()->getRepository("FOMUserBundle:User")->findOneByResetToken($token);
        if (!$user) {
            $mail = $this->container->getParameter('fom_user.mail_from_address');
            return $this->render('FOMUserBundle:Login:error-notoken.html.twig', array(
                'site_email' => $mail));
        }

        $this->setResetToken($user);

        return $this->redirect($this->generateUrl('fom_user_password_send'));
    }
206723
public static String generateToken() {
        String timestampByBase64 = Utils.rightTrim(Base64.encode(String.valueOf(System.currentTimeMillis())), "=");
        return (RandomUtil.simpleUUID() + timestampByBase64).toLowerCase();
    }
1259605
static function getToken($url, $login, $password) {
	    $responseEntity = RestHelper::post($url, [
		    'login' => $login,
		    'password' => $password,
	    ]);
	    if(!$responseEntity->is_ok) {
		    return null;
	    }
	    $token = self::getTokenFromResponse($responseEntity);
	    return $token;
    }
255378
def users_create_token(self, user_id=None, username=None, **kwargs):
        """"""
        if user_id:
            return self.__call_api_post('users.createToken', userId=user_id, kwargs=kwargs)
        elif username:
            return self.__call_api_post('users.createToken', username=username, kwargs=kwargs)
        else:
            raise RocketMissingParamException('userID or username required')
1039253
@Remoted
    public IPromise<Object[]> login(String user, String pw, String jwt) {
        Promise res = new Promise();
        ConnectionRegistry remoteConnection = connection.get();
        getCredentials(user,pw,jwt).then( (authres, err) -> {
            if ( err != null ) {
                res.reject(err);
            } else {
                String sessionId = remoteConnection != null ? remoteConnection.getSocketRef().getConnectionIdentifier() : null;
                getSession(user,sessionId, authres ).then( (sess,serr) -> {
                    if ( sess != null ) {
                        if ( sessionId != null && sessionStorage != null ) {
                            sessionStorage.putUserAtSessionId(sessionId,user);
                        }
                        res.resolve(new Object[]{sess,authres});
                    } else
                        res.complete(sess,serr);
                });
            }
        });
        return res;
    }
974094
public String signToken(AuthenticatedUser user) {
        Date expiry = new Date(System.currentTimeMillis() + this.jwtTimeout);
        JWTClaimsSet claimsSet = user.toClaimSet(this.jwtIssuer, expiry);
        SignedJWT jwt = this.signToken(claimsSet);
        return jwt.serialize();
    }
599267
def obtain_token(self):
        
        token_end_points = ('token/obtain',
                            'obtain-token',
                            'obtain_token')
        for end_point in token_end_points:
            try:
                return self.auth[end_point]._(page_size=None)['token']
            except BeanBagException as e:
                if e.response.status_code != 404:
                    raise
        raise Exception('Could not obtain token from any known URL.')
842515
@SuppressWarnings("serial")
    public Client loginAsOwner() throws APIError {
        requestToken = service.getRequestToken();
        JSONObject token = post("/api/v1/users/login_as_owner", new HashMap<String, Object>() {
            {
                put("request_token", requestToken.getToken());
            }
        });
        if (token != null && !token.getJSONObject("token").isNullObject()) {
            return loginWithAccessToken(token.getJSONObject("token").getString("oauth_token"),
                    token.getJSONObject("token").getString("oauth_token_secret"));
        } else {
            throw new Unauthorized("Could not get Request Token");
        }
    }
382895
public static Token<EsTokenIdentifier> obtainToken(RestClient client, User user) {
        EsToken esToken = obtainEsToken(client, user);
        return EsTokenIdentifier.createTokenFrom(esToken);
    }
351229
function _loadUserFromToken(){
    return BB
        .bind(this)
        .then(function() {
            return grasshopper.request(this.token).users.current();
        })
        .then(function(user){
            this.user = user;
        });
}
858217
def post(self, request):
        """"""
        serializer = AuthTokenSerializer(data=request.data)

        if serializer.is_valid():
            token, _ = ExpiringToken.objects.get_or_create(
                user=serializer.validated_data['user']
            )

            if token.expired():
                # If the token is expired, generate a new one.
                token.delete()
                token = ExpiringToken.objects.create(
                    user=serializer.validated_data['user']
                )

            data = {'token': token.key}
            return Response(data)

        return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
572923
def post(self):
        
        #1.
        username = request.form.get("username")
        password = request.form.get("password")
        exipres  = 7200
        #expire time(seconds)
        if username and password:
            _authRes = self._getAuthentication(username, password)
        else:
            return {"msg": "invalid username or password"}
        #2.
        if _authRes:
            _payload = self._getUserData(username)
            #3.
            try:
                token = self.jwt.createJWT(_payload, expiredSeconds=exipres)
            except JWTException:
            	return {"msg": "Failed to request token"}
            else:
                return {"token": token}
        else:
            return {"msg": "Authentication failed"}
657984
function getIdToken(forceRefresh) {
  if (activeUser() == null) {
    alertError('No user logged in.');
    return;
  }
  if (activeUser().getIdToken) {
    activeUser().getIdToken(forceRefresh).then(alertSuccess, function() {
      log("No token");
    });
  } else {
    activeUser().getToken(forceRefresh).then(alertSuccess, function() {
      log("No token");
    });
  }
}
1204214
private static EsToken getEsAuthToken(ClusterName clusterName, User user) {
        return user.getEsToken(clusterName.getName());
    }
1136266
public RequestToken login(BaasHandler<BaasUser> handler) {
        return login(null, RequestOptions.DEFAULT, handler);
    }
961818
public synchronized void refreshToken()
	{
		final String refreshToken = this.response.refresh_token;

		this.response = null;
		this.cachedInfo = null;

		final String responseStr = authService.getToken(UserManagerOAuthService.GRANT_TYPE_REFRESH_TOKEN,
		                                                null,
		                                                null,
		                                                clientId,
		                                                clientSecret,
		                                                refreshToken,
		                                                null,
		                                                null,
		                                                null);

		loadAuthResponse(responseStr);
	}