Ошибка invalid token session

I did a simple sign up user interface just to check parse but for some reason every time i try to register a user it gives me this error

this is the code:

final ProgressDialog dlg = new ProgressDialog(this);
    dlg.setTitle("Please wait.");
    dlg.setMessage("Signing up.  Please wait.");
    dlg.show();

    String username_str = username.getText().toString();
    String password_str = password.getText().toString();
    String re_password_str = re_password.getText().toString();
    String email_str = email.getText().toString();
    String phone_str = phone.getText().toString();

    if(!re_password_str.equals(password_str)){
        dlg.dismiss();
        Toast.makeText(this,"Passwords does not match!!",Toast.LENGTH_SHORT).show();
        password.setText("");
        re_password.setText("");
    }else if(email_str.isEmpty()|| phone_str.isEmpty()){
        dlg.dismiss();
        Toast.makeText(this,"email or phone cannot be empty!!",Toast.LENGTH_SHORT).show();

    }else {
        ParseUser new_user = new ParseUser();
        new_user.setUsername(username_str);
        new_user.setPassword(password_str);
        new_user.setEmail(email_str);
        new_user.put("phone", phone_str);
        new_user.signUpInBackground(new SignUpCallback() {
            @Override
            public void done(ParseException e) {
                dlg.dismiss();
                if(e == null){
                    Intent i = new Intent(SignupActivity.this,MainActivity.class);
                    startActivity(i);
                }else{
                    Log.d("signup error", e.toString());
                    Toast.makeText(SignupActivity.this,e.toString(),Toast.LENGTH_SHORT).show();
                }
            }
        });

I’ve already spent 2 days in finding the problem but without any success….

asked Apr 1, 2015 at 8:53

kitsuneFox's user avatar

kitsuneFoxkitsuneFox

1,2433 gold badges18 silver badges31 bronze badges

2

I have deleted manually some data from the Parse Database. After that I was having this error when I was trying to save a new user in background:

com.parse.ParseRequest$ParseRequestException: invalid session token

My solution was to uninstall the apk and install it again. It solved the session problem for me.

Important: I did this in the Debug Database, so uninstalling a Debug App and install it again was fine.

answered Jun 15, 2015 at 21:13

Fernando Cardenas's user avatar

5

You might not have logged out from your previous session. Make sure you have a log out logic. Also check if any of your users have logged in before signing in or signing up another user.

The belog code might help,

    var currentUser = Parse.User.current();
                if (currentUser) {
                    // do stuff with the user
                    Parse.User.logOut();
                } 

Also don’t forget to add e.preventDefault(); in your sign up function.

This is how I had my signUp function..

$('.form-signup').on('submit', function(e) {

        var currentUser = Parse.User.current();
                if (currentUser) {
                    // do stuff with the user
                    Parse.User.logOut();
                } 

        e.preventDefault();
        var user = new Parse.User();

        var username = $('#username').val();
        var password = $('#password').val();
        var email = $('#email').val();

        user.set("username", username);
        user.set("password", password);
        user.set("email", email);

        user.signUp(null, {
            success: function(user) {
                //signup successfull
                alert("user created..!! User name: "+ username);
                window.location = "login.html";
            },
            error: function(user, error) {
                // Show the error message somewhere and let the user try again.
                console.log("Error: " + error.code + " " + error.message);
                //alert("User not created..!! " + error.message);
                $("H5").html("User not created..!! " +error.message);
            }
        });
});

answered Apr 8, 2015 at 10:12

sudheeshcm's user avatar

sudheeshcmsudheeshcm

3,2404 gold badges14 silver badges21 bronze badges

The reason for this problem is that you may be testing another Parse application on the same virtual device so the user credentials are still used for the new application. So, the solution for this is

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Add this line and run your application
        ParseUser.getCurrentUser().logOut();

answered Feb 16, 2017 at 8:44

Ahmed Abdelsalam's user avatar

It is due to data deletion from database but local storage still have that data. So you have to clear data from local storage.

Eg.
For Javascript (browser):

window.localStorage.clear()

For React Native:

AsyncStorage.clear();

For android:
Either clear cache or reinstall app

answered May 8, 2020 at 21:49

Saurav Pratihar's user avatar

Yes I think after signing up a user you might have deleted that row from the users class, so first, write this code in your Activity

if(ParseUser.getCurrentUser()!=null){
   Toast.makeText(this,"yes not null",Toast.LENGTH_SHORT).show();
   ParseUser.logOut();
}
else{
   Toast.makeText(this," null",Toast.LENGTH_SHORT).show();
}

You can find the difference when you run your app, first, it will toast you «yes not null» and after if you run your app again it will show you «null»

Now you can signup your user :)
This worked for me.
Hope it works for you as well.
You can find more info at.

ayorgo's user avatar

ayorgo

2,7731 gold badge25 silver badges35 bronze badges

answered Dec 25, 2018 at 15:47

MOHAN samara's user avatar

1

I manually cleared the session and I had the same problem while trying to sign up a new user from the same device I signed up previously. Clearing the data for the App in DEVICE settings fixed the problem.

answered Dec 5, 2015 at 15:55

Dagi's user avatar

If you encounter this problem in your web app, clear the local storage of all Parse data. On Chrome this is:

  1. Developer Tools (F12)
  2. Application
  3. Local Storage
  4. Choose Parse entries and press Delete key (or Backspace)

answered Apr 2, 2019 at 11:17

user1211030's user avatar

user1211030user1211030

2,6222 gold badges19 silver badges22 bronze badges

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Closed

cgcmart opened this issue

Jul 25, 2020

· 19 comments

Closed

Invalid token session. Please login again

#8133

cgcmart opened this issue

Jul 25, 2020

· 19 comments

Comments

@cgcmart

What version of OpenCart are you reporting this for?
master branch
Describe the bug
A clear and concise description of what the bug is
What section does it affect?

either system/config/default.php line 42:
$_['session_expire'] = 360000;
or php.ini line 15:
session.gc_maxlifetime = 9999998
does not work.

Although the above configures exist, actually session lasting time is not enough to complete some job for admin user or online writer, for instances, fill out all product fields including long description, information article, etc. If your work is in the middle, opencart happens request you login again, you do login, but you are not in your previous scenario, you have to do again.

What else config is missing?

To Reproduce
Steps to reproduce the behavior:

  1. Go to ‘admin/index.php?route=catalog/product&user_token=’
  2. Click on ‘….’
  3. Scroll down to ‘….’
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots / Screen recordings
If applicable, add screenshots or recordings to help explain your problem. Please keep these short and if you can, edit them to point out when/where the problem is.
https://www.useloom.com/ is perfect for screen recording with Chrome or with their desktop app

Server / Test environment (please complete the following information):

  • Local development? Deployed to a web server?
  • Operating system
  • PHP version
  • Apache version
  • Browser(s) tested with [e.g. chrome, safari — if applicable]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

@NancySavage

I believe after reading the recent commits involving the session and php changes, that the intention appeared to be to expire it in an hour? However, I am looking at the session table in my DB and each time I log in, the session is set to expire exactly within 24 minutes each time.

session

It’s sort of annoying. If you don’t actually save/update anything in the dashboard within 24 minutes, you get logged out. Perhaps the intention for the admin dash may have been 24 hours but accidentally turned into 24 minutes? Just a wild guess.

@cgcmart

I searched the issue on forum.opencart.com. It’s a persisting issue often raised without official or solid solution since opencart 1.5.

Although user can login again with saved pwd, it’s unacceptable that unsaved work is gone, instead sometimes redirect you up section, sometime goes to dashboard.

@NancySavage

Eh, I figured it out which I did before but I forgot that I had to redo my server with a new php installation (to upgrade to php 7.4). This has been mentioned on the boards, too. Some servers will not allow you to overwrite the settings (meaning, using the php.ini file in the OC directory). You need to go to your server’s actual php file to edit it. OR — you need to edit your htaccess file. It depends on your host provider how you edit the htaccess file, too. In some cases, people on cheapy shared host plans may need to beg the provider to see if they can change it for them. Unfortunately, I have learned the hard way that not all htaccess file settings are the same across various host providers.

So even if you have: session.gc_maxlifetime = 9999998 in opencart’s php.ini file, if you go to your server’s actual php file, it could be set to 1440. Hence, why I saw the expiration for exactly 24 minutes when looking at my DB for the session.

You can see a screenshot of my localhost php file for example where the same thing holds true in this case. I had to change it to be an hour (or 3600 value).

sessionset

I don’t feel this is really an OC issue as a result, as I don’t think you can implement a universal solution for people’s host provider settings (nor for those testing on local environments).

@cgcmart

I do think it’s an OC issue.
I use Cpanel server, ea-php73, that is, php 7.3
When I logged in Cpanel, my domain home, phpmyadmin, stayed a couple of days to expire.

Also refer to #8141 although the reported version is oc 3.0.3.3.

My Cpanel MultiPHP INI Editor Configure PHP INI basic settings show
session.gc_maxlifetime = 9999998

Conclusion: OC session_expire does not work. It’s some confusion between «expire» and «max-age», need the conversion of session_expire into max-age.

  • upload/catalog/controller/common/cookie.php
  • upload/catalog/controller/common/language.php
  • upload/admin/controller/startup/startup.php
  • upload/catalog/controller/startup/marketing.php
  • upload/catalog/controller/startup/startup.php
  • upload/system/framework.php
  • opencart/upload/system/config/default.php
  • upload/system/helper/general.php
  • upload/system/library/session.php
  • upload/system/library/session/db.php
  • upload/system/library/session/file.php

Syntax:

Set-Cookie: <cookie-name>=<cookie-value>; Expires=<date>
Set-Cookie: <cookie-name>=<cookie-value>; Max-Age=<non-zero-digit>

According mozilla developer set-cookie:

Expires=<date> Optional

    The maximum lifetime of the cookie as an HTTP-date timestamp. See Date for the required formatting.

    If unspecified, the cookie becomes a session cookie. A session finishes when the client shuts down, and session cookies will be removed.

Max-Age=<number> Optional
    Number of seconds until the cookie expires. A zero or negative number will expire the cookie immediately. If both Expires and Max-Age are set, Max-Age has precedence.

up-to-date browsers fully support max-age:
set-cookie

//
I am going to replace session_expire with session_cookie_lifetime, that will be easier way, consistent with php config, and supported by all browsers.

Lines like:
$_['session_cookie_lifetime'] = 86400;

'max-age' => time() + $this->config->get('session_cookie_lifetime'),

4 files need edit:

  1. upload/system/config/default.php
  2. upload/admin/controller/startup/startup.php
  3. upload/catalog/controller/startup/startup.php
  4. upload/system/framework.php

//

Made the above changes and solved the issue for oc master branch. Opencart will not throw out «Invalid token session. Please login again» for 24 hours if you are logged in.

@NancySavage

Did you restart apache after making the changes? It’s required after editing php.ini for the changes to take effect.

@danielkerr

ok changed max-age back to expire.

@danielkerr

i think the expire time issue with session is because the db and php time settings are not synced properly.

@danielkerr

maybe i need to replace all the NOW statements with php date();

@cgcmart

@danielkerr

@cgcmart

Yes, it’s. Website complete seo urls show as expected.

@danijelGombac

What I tested the «error not found» is not working as expected. The home page is loaded instead.

@cgcmart

@danijelGombac

After last change for seo

http://localhost/oc_4/en-gb/laptop-notebook is ok
http://localhost/oc_4/en-gb/laptop-not home page, should be error not found

@cgcmart

@danijelGombac

@cgcmart

when you add category and product, you also fill out seo field.

@mhcwebdesign

cgcmart: Your wenbo.world site has many other more severe issues, at the moment it would take more than 10 or 20 minutes to load, especially for the images.

@cgcmart

I noticed. I just managed to install oc 4 master on Sunday. Probably internet traffic, local connection slow, or cache issue. I use Alibaba cloud.

Another site https://cgcmart.com/ is good. I use Google cloud.

Invalid token session. Please login again.


I am able to login to my admin panel up to dashboard.
But every time I click on links in the admin panel such as Catalog, Extension, Design, Marketing, System and others, it takes me again to «Please enter your login details» page with warning Invalid token session. Please login again.

This started to happen yesterday. Before, the site worked just normally. No recent change or addition of extension.

Anyone, please help with fixing this issue.

Thanks.

Re: Invalid token session. Please login again.


Post

by acx » Wed May 02, 2018 12:25 am

Have you made any changes recently?

This tends to happen when the url gets malformed; most commonly, a space between the token =sdgsghuisdjndsui


Re: Invalid token session. Please login again.


Post

by Lamsari » Wed May 02, 2018 12:28 am

No change made recently.

Could you help with how to fix this? Step by step. tks.

Re: Invalid token session. Please login again.


Post

by Lamsari » Wed May 02, 2018 12:33 am

I see the url. no space.
token=rxjz2Yy5NPOiL1z

Re: Invalid token session. Please login again.


Post

by Lamsari » Wed May 02, 2018 1:32 am

Really disappointed with opencart. I have never seen anything like this in my other stores using magento and prestashop.
The only reason I began to use opencart (using opencart 3.0.2) for a new store is that it loads relatively faster than the other two.
But opencart turns out to be really unstable.

The issue happens for no known reason.

Re: Invalid token session. Please login again.


Post

by paulfeakins » Wed May 02, 2018 8:18 pm

Lamsari wrote: ↑

Wed May 02, 2018 1:32 am

Really disappointed with opencart.

This is actually more likely to be a server problem.

Lamsari wrote: ↑

Wed May 02, 2018 1:32 am

I have never seen anything like this in my other stores using magento and prestashop.

Yes you have, Magento is full of issues and you know it.

Lamsari wrote: ↑

Wed May 02, 2018 1:32 am

The only reason I began to use opencart (using opencart 3.0.2) for a new store is that it loads relatively faster than the other two.

Correct.

Lamsari wrote: ↑

Wed May 02, 2018 1:32 am

But opencart turns out to be really unstable.

Incorrect.

Lamsari wrote: ↑

Wed May 02, 2018 1:32 am

The issue happens for no known reason.

Well if you don’t know what the issue is, don’t blame OpenCart, when it’s likely to be your web server.

If you haven’t made any changes to the OpenCart code then it can’t be OpenCart because OpenCart doesn’t change or update itself.

My bet here is that your server has a problem with session files, so you should ask your web host to check those.


UK OpenCart Hosting | OpenCart Audits | OpenCart Support — please email info@antropy.co.uk


User avatar



Joined

Mon Aug 22, 2011 11:01 pm

Re: Invalid token session. Please login again.


Post

by Lamsari » Thu May 03, 2018 1:59 am

No change to the server. Exact server setting and configuration used since I installed this opencart 3.0.2 from the start.
It ran well for a month, all of sudden, invalid token sessions. please login again on using any functionlity in admin panel.

Checked with hosting — nothing changed. Very clear to me, the blame is on OPENCART not hosting.

My other stores (non-opencart) for years never has this invalid token issue. This is the first time I am seeing it — only with OPENCART.

If no one can even offer any solution — clearly it is OPENCART to blame.

Re: Invalid token session. Please login again.


Post

by sw!tch » Thu May 03, 2018 3:15 am

1. Try clearing your bowser cache.

2. Are you opening Admin links in a new tab after logging in?

3. As others have said, it sounds like a server issue with sessions. Do you have mod_security enabled? If so maybe see it’s flagging some rule.

4. Try the live OC demo site, see if you get invalid token there. If not then most likely something you did or something with your server configuration.

It would be helpful to let people know what you have tried rather then bash FREE software. ::)


Full Stack Web Developer :: Send a PM for Custom Work.
Backup and learn how to recover before you make any changes!

Re: Invalid token session. Please login again.


Post

by Lamsari » Thu May 03, 2018 4:37 am

Your steps have been tried.
As I said, site ran smoothly the last one month. A couple of market place extensions were added when it started a month ago. Site worked normally.
This began to happen 2 days ago all of sudden.
No change to server configuration at all.
Why is it so hard for you acknowledge there is something wrong with opencart. I am not bashing . Opencart is simply not a good store. My other stores in the same server never had login and invalid token issues as in Opencart.

Not only there is something wrong, there many wrongs. Why is it hard for you to acknowledge that? Contact us form did not work until I paid someone to fix it. Users can use add to cart button even though products are out of stock. No product filters. Many other issues.

Free? That’s clearly misleading. With basic issues such as invalid token and a lack of basic functionalities — it is not free at all. One has to spend a few hundred dollars to make it work like a normal online store.

Re: Invalid token session. Please login again.


Post

by paulfeakins » Thu May 03, 2018 5:36 pm

Lamsari wrote: ↑

Thu May 03, 2018 4:37 am

As I said, site ran smoothly the last one month. A couple of market place extensions were added when it started a month ago.

Try disabling them and the clearing and refreshing the OCMOD cache.

Lamsari wrote: ↑

Thu May 03, 2018 4:37 am

Not only there is something wrong, there many wrongs. Why is it hard for you to acknowledge that? Contact us form did not work until I paid someone to fix it. Users can use add to cart button even though products are out of stock. No product filters. Many other issues.

If it were true we’d agree, but it’s not. A fresh OpenCart works fine, you’ve somehow messed it up.

Lamsari wrote: ↑

Thu May 03, 2018 4:37 am

Free? That’s clearly misleading. With basic issues such as invalid token and a lack of basic functionalities — it is not free at all. One has to spend a few hundred dollars to make it work like a normal online store.

Absolute rubbish, plenty of our clients run fairly default stores with very few extensions and they work very well.


UK OpenCart Hosting | OpenCart Audits | OpenCart Support — please email info@antropy.co.uk


User avatar



Joined

Mon Aug 22, 2011 11:01 pm

Re: Invalid token session. Please login again.


Post

by Lamsari » Fri May 04, 2018 4:21 am

Rubbish??? All I said there are true.
Add to cart button works even though products are out of stock. This is a basic function that is in other stores. Not in opencart.
How can I disable? Every time I click on cataglog, extensions, etc it show invalid sessions.

You don’t want to acknowloedge how bad opencart is.

Re: Invalid token session. Please login again.


Post

by sw!tch » Fri May 04, 2018 4:34 am

Lamsari wrote: ↑

Fri May 04, 2018 4:21 am


Rubbish??? All I said there are true.
Add to cart button works even though products are out of stock. This is a basic function that is in other stores. Not in opencart.
How can I disable? Every time I click on cataglog, extensions, etc it show invalid sessions.

You don’t want to acknowloedge how bad opencart is.

Troll much?

If it’s so bad then move on to another cart. Why are you still here?

Nobody is going to help you when all you do is whine. Move on or man up and pay someone to properly setup your cart.


Full Stack Web Developer :: Send a PM for Custom Work.
Backup and learn how to recover before you make any changes!

Re: Invalid token session. Please login again.


Post

by paulfeakins » Fri May 04, 2018 4:25 pm

Lamsari wrote: ↑

Fri May 04, 2018 4:21 am

Rubbish??? All I said there are true.

If it were true I’d be the first to admit it. But it’s not.

Lamsari wrote: ↑

Fri May 04, 2018 4:21 am

You don’t want to acknowloedge how bad opencart is.

Actually I found it to be the best of the PHP open source shopping carts after extensive research and testing.

But @sw!tch is right — we provide our time here for free so if you do want help I suggest you ask nicely.


UK OpenCart Hosting | OpenCart Audits | OpenCart Support — please email info@antropy.co.uk


User avatar



Joined

Mon Aug 22, 2011 11:01 pm

Re: Invalid token session. Please login again.


Post

by Sinto001 » Sat Sep 14, 2019 8:37 pm

I am also getting the same error.. Any fix to this problem ????????

Re: Invalid token session. Please login again.


User avatar



Joined

Mon Aug 22, 2011 11:01 pm

Re: Invalid token session. Please login again.


Post

by Sinto001 » Mon Sep 16, 2019 8:22 pm

Lamsari wrote: ↑

Tue May 01, 2018 11:46 pm


I am able to login to my admin panel up to dashboard.
But every time I click on links in the admin panel such as Catalog, Extension, Design, Marketing, System and others, it takes me again to «Please enter your login details» page with warning Invalid token session. Please login again.

This started to happen yesterday. Before, the site worked just normally. No recent change or addition of extension.

Anyone, please help with fixing this issue.

Thanks.

Actually what I came to know is that this occur with certain Internet Service Providers only… I have Airtel Internet and I also faced the same issue. While other support team in other internet providers where able to log in.

Re: Invalid token session. Please login again.


Post

by letxobnav » Mon Sep 16, 2019 8:45 pm

The only conditions which trigger that token error message are:

1) You have a user_token defined in your session (which happens when you login) but there is no user_token in the GET variables of the page.
or
2) You have both defined but they are not the same.

So this is not a «losing the session» issue as that would not trigger either.
My guess is in most cases this is due to a poorly written extension which messes with the user_token in the get variables or
a server setting/module which messes with the get variables.


Crystal Light Centrum Taiwan
Extensions: MailQueue | SUKHR | VBoces

“Data security is paramount at […], and we are committed to protecting the privacy of anyone who is associated with our […]. We’ve made a lot of improvements and will continue to make them.”
When you know your life savings are gone.


User avatar


Re: Invalid token session. Please login again.


Post

by Fabienlolo » Wed Sep 25, 2019 3:26 pm

Could it be Javascript related? I am not sure as you are saying the change comes from nowhere and you did not change anything from your OC files. But i had invalid token issue and got kicked out from adminpanel every single click. It was javascript related and i could solve my issue. So just in case you want to give it a look, see this topic if your browser console gives you javascript issue: viewtopic.php?f=202&t=212504#p765294 Fabienlolo » Wed Sep 25, 2019 6:53 am.
Hope that could help.

Last edited by Fabienlolo on Sat Oct 17, 2020 3:54 pm, edited 1 time in total.

Re: Invalid token session. Please login again.


Post

by phpscript » Fri Aug 21, 2020 7:47 pm

Image
session id problem
please go database open oc_session table and field session_id set «Uniqe» then issue solved.
like see image attachment




Joined

Fri Sep 18, 2015 12:04 am

Re: Invalid token session. Please login again.


Post

by letxobnav » Fri Aug 21, 2020 8:24 pm

Don’t know why you bring a year old thread to life to post this nonsense.


Crystal Light Centrum Taiwan
Extensions: MailQueue | SUKHR | VBoces

“Data security is paramount at […], and we are committed to protecting the privacy of anyone who is associated with our […]. We’ve made a lot of improvements and will continue to make them.”
When you know your life savings are gone.


User avatar


Who is online

Users browsing this forum: No registered users and 44 guests

Introduction

When a user is authenticated in your application, a short-lived session token is generated by Clerk.js that depicts the fact and it’s sent to your backend. Your backend will typically want to validate that the session token is valid (i.e. that it comes from Clerk, that it hasn’t expired etc.)

If you’re using the middlewares provided by our Clerk SDKs, this is all handled automatically in every request. If you’re not using the middlewares, you can still use the respective helpers provided by the SDKs to validate the tokens. That is all good, but if an SDK does not exist for the application’s programming language, you will have to manually validate these tokens.

This guide provides instructions on how to do exactly that; manually validate the Clerk session tokens that your backend receives.

Overview

Your Clerk-generated session tokens are essentially JWTs which are signed using your instance’s private key and can be verified using your instance’s public key. Depending on your architecture, these tokens will be in your backend requests either via a cookie named __session or via the Authorization header.

For every request, you must validate its token to make sure it hasn’t expired and it is authentic (i.e. no malicious user tried to tamper it). If these validations pass, then it means that the user is authenticated to your application and you should consider them signed in.

Instructions

By following the steps below, you can validate the session token on your own and make sure that the user session is still active and valid.

  1. Retrieve the session token from either __session cookie or from the Authorization header
  2. Get your instance’s Public Key. There are 3 ways to do it:
    1. Via the Backend API in JSON Web Key Set (JWKS) format at the following endpoint https://api.clerk.dev/v1/jwks(If there is more than one JWKS, decode your session token, get the token kid from the header part and construct the respective public key)
    2. Via the Frontend API in JSON Web Key Set (JWKS) format at the following endpoint https://<YOUR_FRONTEND_API>/.well-known/jwks.json(If there is more than one JWKS, decode your session token, get the token kid from the header part and construct the respective public key)
    3. If you are planning to use Clerk on a Serverless/Edge Runtime where JWKs caching is challenging, you can use the instance Public Key as an environment variable. The key can be found in Dashboard > API Keys > JWT Verification Key. Note that the JWT Verification key is not in PEM format, the header and footer are missing, in order to be shorter and single-line for easier setup.
  3. Use the above Public Key to verify the token’s signature
  4. Validate that the token is not expired, by checking the exp and nbf claims
  5. If the azp claim exists, validate that equals any of your known Origins that are permitted to generate those tokens. This is an extra security check that we highly recommend that you do

Steps (3) and (4) should better be done by existing JWT libraries of your favourite language

If the above process is successful, it means that the user is signed in to your application and you can consider him authenticated. You can also retrieve the session ID and user ID out of the token’s claims.

Using the JWT Verification Key

As mentioned above, your JWT Verification Key is not in a PEM format. This is to avoid having to use «multiline environment variables» which are difficult to use in many systems/environments. In order to get a properly formatted public key from you will need to transform it slightly.

Transform steps:

  • Split the JWT Verification Key into chunks of 64 characters
  • Join the chunks separated with a newline character n
  • Append, and prepend the appropriate header and footer
    • Header: -----BEGIN PUBLIC KEY-----n
    • Footer: n-----END PUBLIC KEY-----

The output should look something like the following:

1

-----BEGIN PUBLIC KEY-----

2

MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwXbBOUbeOfvxtIUDNDBb

3

77J66FTRpJhB/o3OwQhjYAgcJ1XLEenzUKiczq8b1zJ/xcqdWT4TYamFthcdv/sD

4

zmS13DbHHlkYVfE6hG1sG0r/ahCWORi3F2WZT9u7rjwli3A647e5eHdy3qD/tvcB

5

E42UmRmcL2mbedaQiVy2i5U5qlIXI6YAC+BYiVdw5YOrGNQWzoAHX8kBmwjMWQTQ

6

4AKvSZHYf3Mtd0ni0LTmZD8WXvGbQr4Ia5caZfyGzFkPPbNFSXzyT9yJZOB281HP

7

hMUlECYRmPlHloBZBArowkQRk5rlLKu+tdpUp0B7hJcHTAcgn7qZuecIZX4EmVWM

9

-----END PUBLIC KEY-----

The code below, is an example implementation written in javascript:

1

const splitPem = process.env.CLERK_JWT_VERIFICATION_KEY.match(/.{1,64}/g);

2

const publicKey = "-----BEGIN PUBLIC KEY-----n" + splitPem.join("n") + "n-----END PUBLIC KEY-----"

Putting it all together

1

import type { NextApiRequest, NextApiResponse } from 'next';

2

import Cookies from 'cookies';

3

import jwt from 'jsonwebtoken';

5

export default async function (req: NextApiRequest, res: NextApiResponse) {

6

const splitPem = process.env.CLERK_JWT_VERIFICATION_KEY.match(/.{1,64}/g);

8

'-----BEGIN PUBLIC KEY-----n' +

10

'n-----END PUBLIC KEY-----';

12

const cookies = new Cookies(req, res);

13

const sessToken = cookies.get('__session');

15

res.status(401).json({ error: 'not signed in' });

19

var decoded = jwt.verify(sessToken, publicKey);

21

res.status(400).json({

22

error: 'Invalid Token'

27

res.status(200).json({ sessToken: decoded });

1

import Cookies from 'cookies';

2

import jwt from 'jsonwebtoken';

4

export default async function (req, res) {

5

const splitPem = process.env.CLERK_JWT_VERIFICATION_KEY.match(/.{1,64}/g);

7

'-----BEGIN PUBLIC KEY-----n' +

9

'n-----END PUBLIC KEY-----';

11

const cookies = new Cookies(req, res);

12

const sessToken = cookies.get('__session');

14

res.status(401).json({ error: 'not signed in' });

18

var decoded = jwt.verify(sessToken, publicKey);

20

res.status(400).json({

21

error: 'Invalid Token'

26

res.status(200).json({ sessToken: decoded });

0 Пользователей и 1 Гость просматривают эту тему.

  • 100 Ответов
  • 88963 Просмотров

Проблема такова. Регистрация на сайте как таковом не нужна. Но еще установлен VirtueMart 1.1.3 + Joomla 1.5.14. Для регистрации использую mod_virtuemart_login. Много всего перечитал, что нашлось в поиске. Выполнил действия с кэшем, очистил таблицу с сессиями в БД, ничего не помогает.
А проблема то вот в чем. Допустим при входе или выходе из модуля авторизации VirtueMart перекидывает на такую пустую страницу, с надписью «Invalid Token»

/index.php?option=com_user&task=logout

В стандартном модуле Joomla перекидывает на

index.php

пишется та же ошибка, но при обновлении страницы лечится (в случае выше нет)
Нужен ваш хэлп как это исправить, или хотя бы сделать чтобы из модуля виртуемарта перекидывало на главную, там хоть если обновить то работает.
Если бы только я пользовался этим модулем, т.е. не было бы магазина и надобности в регистрации, то просто бы стирал лишнее в ссылке в строке ввода браузера и опять попадал на главную. Но помимо меня есть еще пользователи.:'(

« Последнее редактирование: 01.12.2010, 21:49:39 от 4webspot »

Записан

СПАСИБО за совет. Реально заработало!

У меня нету магазина, но есть CB и та же проблема.
При авторизации mysite.ru — все ок, а с www.mysite.ru — invalide token. Помогите.

Решил эту проблему путем настройки файла .htaccess в корневой директории где лежит Joomla если его нет создайте его с помощью Блокнота только удалите .txt из имени.

Обратите внимание файл имеет вид .htaccess а не htaccess.txt или .htaccess.txt

В файле должно быть прописано следующее и сохранен он должен быть в директории где joomla

##
# @version $Id: htaccess.txt 10492 2008-07-02 06:38:28Z ircmaxell $
# @package Joomla
# @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved.
# @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
# Joomla! is Free Software
##

#####################################################
#  READ THIS COMPLETELY IF YOU CHOOSE TO USE THIS FILE
#
# The line just below this section: 'Options +FollowSymLinks' may cause problems
# with some server configurations.  It is required for use of mod_rewrite, but may already
# be set by your server administrator in a way that dissallows changing it in
# your .htaccess file.  If using it causes your server to error out, comment it out (add # to
# beginning of line), reload your site in your browser and test your SEF url's.  If they work,
# it has been set by your server administrator and you do not need it set here.
#
#####################################################

##  Can be commented out if causes errors, see notes above.
Options +FollowSymLinks

#
#  mod_rewrite in use

RewriteEngine On

RewriteCond %{HTTP_HOST} ^presentall.ru$
RewriteRule ^(.*)$ http://www.presentall.ru/

########## Begin - Rewrite rules to block out some common exploits
## If you experience problems on your site block out the operations listed below
## This attempts to block the most common type of exploit `attempts` to Joomla!
#
# Block out any script trying to set a mosConfig value through the URL
RewriteCond %{QUERY_STRING} mosConfig_[a-zA-Z_]{1,21}(=|%3D) [OR]
# Block out any script trying to base64_encode crap to send via URL
RewriteCond %{QUERY_STRING} base64_encode.*(.*) [OR]
# Block out any script that includes a <script> tag in URL
RewriteCond %{QUERY_STRING} (<|%3C).*script.*(>|%3E) [NC,OR]
# Block out any script trying to set a PHP GLOBALS variable via URL
RewriteCond %{QUERY_STRING} GLOBALS(=|[|%[0-9A-Z]{0,2}) [OR]
# Block out any script trying to modify a _REQUEST variable via URL
RewriteCond %{QUERY_STRING} _REQUEST(=|[|%[0-9A-Z]{0,2})
# Send all blocked request to homepage with 403 Forbidden error!
RewriteRule ^(.*)$ index.php [F,L]
#
########## End - Rewrite rules to block out some common exploits

#  Uncomment following line if your webserver's URL
#  is not directly related to physical file paths.
#  Update Your Joomla! Directory (just / for root)

# RewriteBase /

########## Begin - Joomla! core SEF Section
#
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/index.php
RewriteCond %{REQUEST_URI} (/|.php|.html|.htm|.feed|.pdf|.raw|/[^.]*)$  [NC]
RewriteRule (.*) index.php
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
#
########## End - Joomla! core SEF Section

В файле может и много лишнего кода но главные две строчки тут это и распологаться они должны сразу после строки RewriteEngine On

RewriteCond %{HTTP_HOST} ^presentall.ru$
RewriteRule ^(.*)$ http://www.presentall.ru/

Делают они следующее если пользователь обращается к сайту по адресу presentall.ru то сделать редирект на www.presentall.ru (который должен быть указан во всех настройках Joomla как основной адрес сайта)

Все проблема решена!

путем настройки файла .htaccess в корневой директории решить проблему не удалось. Более того, при переносе на www слетает некоторый функционал в админке
Invalid Token остался.
Помойму глюк в com_user. Буду разбираться…

« Последнее редактирование: 14.03.2010, 19:39:46 от dimanus »

Записан

у меня наоборот после того как убрал www то ищезло инвалид токен :laugh:

но исчезли все пункі виртуал марка

проблемы в компоненте юзер нет… проблема либо в модули либо в неправильной настройке конфига сайта… редирект на www вам поможет если вы жестко прописали в конфиге что сайт с www… из личного опыта такие же проблемы возникают с модулем авторизации от YOO… и еще с рядом расширений. С чистой Joomla я таких проблем не встречал.

Записан

Хочется уникальное расширение? ===>>>> JoomLine — Разрабатываем расширения под заказ.
Использую хостинг TimeWeb и Reg

В файле VirtueMart.cfg.php добавьте www перед адресом вашего сайта.     http://site.com —>>> http://www.site.com

Cпасибо большое!

Проблема случилась при переносе сайта интернет магазина (VirtueMart) на хостинг, на локалке все было в порядке. При попытке зарегистрироваться вылезала ошибка Invalid Tolken. Модуль авторизации использовался VirtueMart.

Помогло: В файле VirtueMart.cfg.php добавьте www перед адресом вашего сайта.     http://site.com —>>> http://www.site.com

Но: при попытке залогиниться c mysite.ru выбрасывалась ошибка. С www.mysite.ru все стало в порядке.

Помогло: поставить .htaccess редирект, добавив строчки перед строчками с RewriteCond  

## fix invalid token
RewriteCond %{HTTP_HOST} ^вашсайт.зона(например com) [NC]
RewriteRule (.*) http://www.вашсайт.зона(например com)/$1 [L,R=301]

Спасибо за это Alisandre78
В чем возможно причина.. цитирую «есть какая — то проблемка с ссылками на сайт с www. и без www.Исходя  из этого, нужно чтобы ссылка на регистрацию из виртумартовского модуля логин — шла на тот адрес сайта, который прописан в настройках конфига Joomla — лив сайт адрес. И такой же адрес (с с www. или без www) должен быть прописан в настройках безопасности VirtueMart (вкладка настройки — безопасность — там 2 адреса — должны быть одинаковыми). Если проблема не искореняется используем плагин для редиректа на один из адресов с с www. или без www «

Всем спасибо, что можно найти решение, надеюсь кому-то тоже пригодится.. ^-^ *DRINK*

ps. также вначале была проблема с двойной авторизацией администратора — приходилось два раза вводить логин и пароль, вышесделанное устранило этот косяк тоже.

« Последнее редактирование: 28.01.2011, 13:26:20 от smart »

Записан

У меня сейчас похожая проблема. Если не авторизован на сайте при открытии браузера, то при входе — Invalid token, жмешь Назад — оказываешься уже авторизованным. Если после этого выйти из аккаунта и залогиниться заново, ошибок не возникает. Но если при следующем открытии сайта или браузера окажешься неавторизованным, то все опять повторяется. Это при site.com. При www.site.com вообще почти всегда Invalid token. Уже не знаю что делать.

Между прочим, так и не могу решить эту проблему. Ещё один диагноз — вводя site.com/index.php я авторизован, а просто site.com — нет, плюс еще с www не понятны дела. В общем, под разными именами сайт живет разными жизнями. Уже замучил этот баг, помогите кто-нибудь  :O

В общем, поизучав эту проблему, пришел к такому выводу.
Глючат сессии. На страницах с index.php, и без него, они идут параллельно. Без index.php у меня только главная страница. Если не можете помочь с решением этой проблемы, подскажите хотя бы, как сделать, чтобы с главной редиректило на главную/index.php.

Cпасибо большое!

Проблема случилась при переносе сайта интернет магазина (VirtueMart) на хостинг, на локалке все было в порядке. При попытке зарегистрироваться вылезала ошибка Invalid Tolken. Модуль авторизации использовался VirtueMart.

Помогло: В файле VirtueMart.cfg.php добавьте www перед адресом вашего сайта.     http://site.com —>>> http://www.site.com

Но: при попытке залогиниться c mysite.ru выбрасывалась ошибка. С www.mysite.ru все стало в порядке.

Помогло: поставить .htaccess редирект, добавив строчки перед строчками с RewriteCond  

## fix invalid token
RewriteCond %{HTTP_HOST} ^вашсайт.зона(например com) [NC]
RewriteRule (.*) http://www.вашсайт.зона(например com)/$1 [L,R=301]

Спасибо за это Alisandre78
В чем возможно причина.. цитирую «есть какая — то проблемка с ссылками на сайт с www. и без www.Исходя  из этого, нужно чтобы ссылка на регистрацию из виртумартовского модуля логин — шла на тот адрес сайта, который прописан в настройках конфига Joomla — лив сайт адрес. И такой же адрес (с с www. или без www) должен быть прописан в настройках безопасности VirtueMart (вкладка настройки — безопасность — там 2 адреса — должны быть одинаковыми). Если проблема не искореняется используем плагин для редиректа на один из адресов с с www. или без www «

Всем спасибо, что можно найти решение, надеюсь кому-то тоже пригодится.. ^-^ *DRINK*

ps. также вначале была проблема с двойной авторизацией администратора — приходилось два раза вводить логин и пароль, вышесделанное устранило этот косяк тоже.

спасибо сторки в .htaccess помогли!

« Последнее редактирование: 05.05.2011, 14:32:14 от smart »

Записан

Сначала вылетало сообщение Invalid Token  почистил jos_session удалил кеш, «стала вылетать ошибка Время жизни сессии истекло, авторизуйтесь снова». Причем добавление двух строчек в .htaccess не помогло при этом вообще сервер отказывался сайт открывать, и выдавал ошибку 500. Кто нить знает в чем действительно дело, т.к почитав форум такое ощущение что исправление ошибок это сплошное шаманство а не реальное решение проблемы.

« Последнее редактирование: 28.10.2010, 12:17:04 от web_abuser »

Записан

Вобщем проблема походу четко отслеживается, Joomla различает адресс сайта т.е http://www.site.ru/  и http://site.ru/ т.е если в настройках жестко забито то или иное название то после заполнения формы регистрации то программный код перекидывает на жестко забитый УРЛ. но если изначально он не совпадал, то возникает ошибка. Вероятно это задумывалось как защита от взлома. Поэтому походу выход один — сайт должен полностью работать под жестко заданным УРЛом, т.е проблема решается добавлением двух строчек в файл .htaccess. Но тут сразу же возникает вторая проблема, например у меня на хостинге такое не работает. Сервер сразу показывает пустой экран с ошибкой 500. Рою дальше.

Первый вариант не срабатывал на сервере
RewriteEngine On
#RewriteCond %{HTTP_HOST} ^site.com$
#RewriteRule ^(.*)$ http://www.site.com/

Сработал вариант добавления строчек в .htaccess от пользователя urauraura
 а именно

RewriteEngine On
## fix invalid token
RewriteCond %{HTTP_HOST} ^site.com [NC]
RewriteRule (.*) http://www.site.com/$1 [L,R=301]

Спасибо пользователям за подсказки.
Тестирую дальше. пока вроде работает.

« Последнее редактирование: 28.10.2010, 13:56:23 от web_abuser »

Записан

Короче, не знаю что делать, проблема не исчезает никак. Придётся наверное сносить всё нафиг, и заново устанавливать. Хотя уже сомневаюсь, что это поможет.

Я тоже с этой бякой долго мучался. Понял я это дело так.

Глюки возникают из-за того, что сайт существует в двух ипостасях —  www.mysite.ru (субдомен) и просто mysite.ru . При различных действиях и условиях (вроде авторизации с отмеченной галкой «запомнить») юзера перебрасывает с одного сайта, на другой. При этом вылезает invalid token, т.к. авторизовывались мы на одном сайте, а попали уже на другой сайт — и здесь мы вроде как не авторизованы. В общем возникает путаница, из-за чего сессия падает. Я нашел такое решение: прописал в настройках вирта адрес сайта (советую без www — просто mysite.ru), а потом настроил жесткое перенаправление со всех адресов с www.mysiteru/* на mysite.ru. Оба действия здесь описывались, надо их только совместить для полной надежности. Мне помогло.

P.S. Похоже протупил, все уже давно описали.

« Последнее редактирование: 03.11.2010, 23:56:30 от lezvoed »

Записан

Да у меня даже вирта нет, а все равно косяки )))

Вот одна из типичных ситуаций моей проблемы:
Отключаю сайт в настройках, закрываю браузер. Открываю заново, захожу на сайт, сайт виден, но я не авторизован. Перейдя на какую-нибудь страницу (новости, например), оказываюсь авторизованным. Если же вместо этого логинюсь с главной — Invalid token (после чего, нажав Назад, возвращаюсь уже авторизованным)

« Последнее редактирование: 04.11.2010, 00:00:54 от Yavich »

Записан

А кнопку «Выйти» перед закрытием браузера жали? По-моему сайт отключается только для уже завершенных сессий. Возможна такая ситуация — сессия корректно не завершена, поэтому а) сайт вам показывается б) при попытке авторизоваться возникает ошибка, т.к. сайт вообще отключен, и главную как бы вообще нельзя увидеть г) жмакаете «назад» и снова видите сайт, т.к. сессия по-прежнему не завершилась.

Нет, выйти конечно не жал. Дело не в том, что сайт выключен, это я просто привёл пример.
Даже когда включен — заходишь, логинишься (с кнопкой Запомнить), потом закрываешь ьраузер, открываешь, заходишь неавторизованным, обновишь страницу — авторизуешься автоматически, а если попытаешься логиниться — Invalid Token. В общем, сессия как будто бы ещё продолжается, но модуль авторизации предлогает логиниться

Можно и без www, главное чтобы при кэшировании, все модули имели такое же время жизни кэша как и в глобальных настройках. При этом, если идет связка с каким-нибудь  внешним скриптом (например форумом через Jfusion), то и для него нужно установить такое же время жизни кэша.
При этом не забываем отключить кэширование у модуля входа.
Так что, немного поколдовав, я добился полного исчезновения Invalid Token.

Записан

Сон разума порождает монстров

Фрилансом не занимаюсь. Никому ничего не должен. Отвечаю по мере знания и умения. — JFusion — Наше всё! Joomla 1.5.23 SMF 1.1.15 JFusion 1.5.6 JComments 2.2.0 JoomGallery 1.5.6.4 JDownloads 1.8

Спасибо, с помощью .htaccess вопрос решен!

Народ, кому интересно, нашел выход/решение, короче как избавиться от ошибки.
Проблема была немного в другом: для своего сайта мама-папа.ру нашел автора — девушка психолог, которая согласилась написать пару статей о психологии детей. Мне нужно было открыть ей возможность Автора, но получался глюк, в том, что когда она заходила на сайт, и нажимала сохранить статью, то следующая страница была белая с ошибкой Invalid Token. Я тоже и кэш чистил, и старый кэш, и таблицы jos_session в базе, и все куки удалял, и отключал в Joomle кэширование — ничего не помогало. Выход нашелся неожиданный. Вход на сайт происходит через модуль шаблона (сверху у солдатика), смотрите на  и если нажимать на выход из этого же модуля, то получается, что вы не вышли до конца. И в последующих входах Joomla не понимает/путается кто вошел. Следовательно выдает ошибку Invalid Token. Я попробовал один раз выйти с помощью модуля самой Joomla, если зарегиться, то он появляется справа. Так вот, если сделать выход через него, а потом опять войти, и сохранить статью, то ошибки не будет. 

помогите разобратся с проблемой
после долгого прибывания на сайте на одной любой странице ,когда переходиш на другую выдает такое;

хотя я был авторизован на сайте,вводиш логин , пароль выдаёт Invalid Token. Если вернутся назад и просто перегрузить страницу проходит авторизация
проблема появилась недавно,до этого пол года было все нормально
вот сайт

« Последнее редактирование: 04.12.2010, 00:01:21 от aaleks74 »

Записан

Нет, выйти конечно не жал. Дело не в том, что сайт выключен, это я просто привёл пример.
Даже когда включен — заходишь, логинишься (с кнопкой Запомнить), потом закрываешь ьраузер, открываешь, заходишь неавторизованным, обновишь страницу — авторизуешься автоматически, а если попытаешься логиниться — Invalid Token. В общем, сессия как будто бы ещё продолжается, но модуль авторизации предлогает логиниться

вот у меня таже проблема, интересно выход нашелся ?
вот бывает и такое при переходе с http://мой сайт.ru / на http://мой сайт.ru /index.php


## fix invalid token
RewriteCond %{HTTP_HOST} ^вашсайт.зона(например com) [NC]
RewriteRule (.*) http://www.вашсайт.зона(например com)/$1 [L,R=301]

Помогло, спс yes!

вот у меня таже проблема, интересно выход нашелся ?
вот бывает и такое при переходе с http://мой сайт.ru / на http://мой сайт.ru /index.php

Нет, выход до сих пор не найден, перерыл весь интернет — куча решений, но все мимо, сам пробовал всё что можно — не помогает, у друзей веб-программистов спрашивал — не знают. Бред…
Жду финальной версии 1,6, придётся переходить на неё, по ходу это единственный выход :(

Понравилась статья? Поделить с друзьями:
  • Ошибка invalid token pubg
  • Ошибка inst 08105 04
  • Ошибка invalid stream format
  • Ошибка insp2 на опель корса
  • Ошибка invalid session minecraft