Jwt expired error

Why do I get this error? let jwt = require('jsonwebtoken'); let jwt_decode = require('jwt-decode'); let secret = "The Secret String"; let oHeader = { "alg": &quo...

Why do I get this error?

let jwt = require('jsonwebtoken');
let jwt_decode = require('jwt-decode');

let secret = "The Secret String";

let oHeader = {
    "alg": "HS256",
    "typ":"JWT"
};

let oPayload = {
    "fname": "John",
    "lname": "Doe",
    "role": "admin",
    "exp": 3600 // Do you see this? It is 1 (one) hour, isn't it?
}

Now let’s create and then verify a token:

let token = jwt.sign(oPayload, secret);

console.log('[token] ', token);
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmbmFtZSI6IkpvaG4iLCJsbmFtZSI6IkRvZSIsInJvbGUiOiJhZG1pbiIsImV4cCI6MzYwMCwiaWF0IjoxNDc1ODIyNTc4NDYyfQ.HKfpUkfRE2s7uMmgwU627RqnjOB4XROk22QzOFtRpXw

// First, let's see the payload with "jwt_decode"
console.log('[jwt_decode(token)]', jwt_decode(token));
 { fname: 'John',
  lname: 'Doe',
  role: 'admin',
  exp: 3600,
  iat: 1475823292188 } 

// Now with "jwt.decode(token)"
console.log('[jwt.decode(token)]', jwt.decode(token));
 { fname: 'John',
  lname: 'Doe',
  role: 'admin',
  exp: 3600,
  iat: 1475823292188 } 

// And now let's verify a token
console.log('[jwt.verify(token, secret)]', jwt.verify(token, secret));

C:Usersusersboxnodeappnode_modulesjsonwebtokenverify.js:32
      if (err) throw err;
               ^
TokenExpiredError: jwt expired
    at Object.module.exports [as verify] (C:Usersusersboxnodeappnode_modulesjsonwebtokenverify.js:121:19)
    at Object.<anonymous> (C:Usersusersboxnodeappassetsjsreactdevdraftsjwt.js:37:70)
    at Module._compile (module.js:541:32)
    at Object.Module._extensions..js (module.js:550:10)
    at Module.load (module.js:458:32)
    at tryModuleLoad (module.js:417:12)
    at Function.Module._load (module.js:409:3)
    at Module.runMain (module.js:575:10)
    at run (bootstrap_node.js:352:7)
    at startup (bootstrap_node.js:144:9)
[Finished in 0.4s with exit code 1]
[shell_cmd: node C:Usersusersboxnodeappassetsjsreactdevdraftsjwt.js]
[dir: C:Usersusersboxnodeappassetsjsreactdevdrafts]
[path: C:Windowssystem32;C:Windows;C:WindowsSystem32Wbem;C:WindowsSystem32WindowsPowerShellv1.0;C:Program Filesnodejs;C:Ruby22-x64bin;C:Program FilesAmazonAWSCLI;C:Program Files (x86)SkypePhone;C:UsersuserAppDataRoamingnpm]

Why does it happen? How to fix?
«version»: «7.1.9»

Содержание

  1. JWT (JSON Web Tokens) Errors | Invalid JWT Signature
  2. JWT Errors
  3. Invalid JWT Signature: invalid_grant
  4. How to Fix | Adding New Service Account Key
  5. Wrap up
  6. ExpiredSignatureError: Signature has expired — returns 500 instead of 400 #159
  7. Comments
  8. ERROR: The JWT token has expired: Signature has expired. FIX #2402
  9. Comments
  10. Bug Report
  11. Expected behavior:
  12. Actual behavior:
  13. Detailed steps to reproduce:
  14. Release or development git branch? Please note the release version or commit hash:
  15. Operating system and version (eg: Windows 10, OS X 10.9, OS X 10.11, Ubuntu 16.10):
  16. Other relevant information:
  17. Usage Examples¶
  18. Encoding & Decoding Tokens with HS256В¶
  19. Encoding & Decoding Tokens with RS256 (RSA)В¶
  20. Specifying Additional Headers¶
  21. Reading the Claimset without Validation¶
  22. Reading Headers without Validation¶
  23. Registered Claim Names¶
  24. Expiration Time Claim (exp)В¶
  25. Not Before Time Claim (nbf)В¶
  26. Issuer Claim (iss)В¶
  27. Audience Claim (aud)В¶
  28. Issued At Claim (iat)В¶
  29. Requiring Presence of Claims¶
  30. Retrieve RSA signing keys from a JWKS endpoint¶
  31. OIDC Login Flow¶

JWT (JSON Web Tokens) Errors | Invalid JWT Signature

Errors are the best especially when they are written in a way where you become a decipherer. I remember the good old days when all the error codes I got were only numbers and maybe letters mixed in and there wasn’t any online searching to easly get interpretations.

I’ve been working with Google Cloud products and connecting to services from my laptop like Storage and BigQuery. Over the last several months, I’ve hit up against a JWT error, invalid_grant:Invalid JWT Signature , a couple times, and below provides an overview of how I resolved it, which was basically updating the expired service account key.

JWT Errors

“The mechanics of server-to-server authentication interactions require applications to create and cryptographically sign JSON Web Tokens (JWTs).” JWTs are signed tokens to authenticate your server to server connections.

This page on Using OAuth 2.0 for Server to Server Applications has a section in the middle called JWT error codes which gives more details about the different errors you may see and how to resolve them. Its a good place to start for more information.

Invalid JWT Signature: invalid_grant

For my error, invalid_grant:Invalid JWT Signature , the way to resolve wasn’t included in the list under JWT error codes. Basically, the Service Account key expired, and I needed to generate a new one.

I did find someone in a StackOverflow thread who helped me hone in on this with this comment: The JWT assertion is signed with a private key not associated with the service account identified by the client email.

I thought for a moment the email under my local gcloud config might be the problem, but it ended up being the expired key. Thus, the key was not associated with the service account anymore.

How to Fix | Adding New Service Account Key

In order to fix this, go to the APIs & Services on the Google Cloud Console.

Look under Service Accounts, for the email account you are using for your project.

If you don’t remember what that email address is then you can look it up with the command.

On Google Cloud Console, choose the edit symbol next to that email account you are using.

Choose the Keys section.

Check if your service account key is Active or Expired.

If you don’t know what the service account key is that you are using, look at the file you are using on your computer which is probably under

/.oauth, especially if you are on a Mac. If not then look at the file path associated with GOOGLE_APPLICATION_CREDENTIALS environment variable to find the service account key file.

Part of the key number may be in the file name; otherwise, it will be inside the service account key file.

If a key has Expired then choose Add Key which will add one that is Active and download a json service account key file to your computer.

Move that json key file to where you reference your files. Some gcloud server connections automatically look under

/.oauth, but you can change that location with the GOOGLE_APPLICATION_CREDENTIALS environment variable.

If you have GOOGLE_APPLICATION_CREDENTIALS environment variable defined in your

/.bash_profile file then make sure to update the location there.

Wrap up

This post reviews JWT errors and specifically how to resolve the invalid_grant:Invalid JWT Signature error. For Invalid JWT Signature, check if your service account key has expired. Go to your APIs & Services to add a new key if it has.

Источник

ExpiredSignatureError: Signature has expired — returns 500 instead of 400 #159

Given a expired token, the server returns a 500 and the message:

It should be somehow a 401 or maybe give a chance to renew the token (I don’t know if that’s possible getting at this point.

The text was updated successfully, but these errors were encountered:

@sneridagh the server should return a 401 (unauthorized). I think the client should take care of the token renewal. Auto-renewing the token feels to be a bit too much to me. @buchi opinions?

@sneridagh I just double checked and it turns out the current implementation is correct. An invalid token returns a HTTP 400, which is correct according to the RFC:

The authorization server responds with an HTTP 400 (Bad Request)
status code (unless specified otherwise) and includes the following
parameters with the response:

Please provide us with the necessary information to reproduce the 500 you encountered.

@sneridagh I added a test to show that the server returns a 400 response:

@tisto It would be difficult to reproduce (and test), since you need an expired token. The raise came directly from jwt.api_jwt, maybe we can intercept it and put the correct 400 status code in the response instead of the 500.

@sneridagh right. I would like to write another test to trigger that problem. I just need to figure out how to generate an expired token. @buchi do you have a pointer for me?

(Side note: Renewal of already expired tokens would completely defeat the purpose of token expiration, no? Otherwise an attacker could always renew a long expired token that he intercepted once)

@sneridagh I created a functional test case for auth from the scratch:

I still can not reproduce the problem. What kind of resource do you try to access?

Here is the full pull request:

using pyjwt==1.7.1 and having the same problem. catching the exception and re-raising seems like a backwards solution 🙁

er never mind, in my case it was Flask re-raising it as 500. I just added this handler:

I got the same problem as @squarewave24 , same pyjwt version.
But it weird, I only get this error when running my api on heroku worker, on my local machine it works as expected (return 401)

Источник

ERROR: The JWT token has expired: Signature has expired. FIX #2402

Bug Report

Expected behavior:

Actual behavior:

JWT token error, The JWT token has expired: Signature has expired

Detailed steps to reproduce:

  1. Open ‘PYFA’
  2. Open ‘Character’
  3. Open ‘Manage ESI Characters’
  4. Click ‘Add Character’
  5. Enter ESI and get base64 string (Manual method)
  6. Get local server startup error

Release or development git branch? Please note the release version or commit hash:

The version was obtained via ‘git clone’.

Operating system and version (eg: Windows 10, OS X 10.9, OS X 10.11, Ubuntu 16.10):

Other relevant information:

When checking the token, the program considers it ‘obsolete’, after googling a little, I found out that the ‘exp’ parameter in the token itself is responsible for this. The check takes place in the ‘esiAccess.py’ file, ‘services’ folder.

After a little searching, I realized that you use the ‘python-jose’ library to work with jwt tokens, by opening its code and finding the decode method, I found the ‘_validate_exp’ method in which the token is checked for ‘validity’.

As it turned out, the library developers use the current time zone of my computer (+3:00) and the time specified in the JWT token is in the zone (+0:00), which is why the token is immediately considered ‘not valid’.

A quick fix error on the user’s side can be corrected by changing the clock, in my case it worked. On the part of the developer, you can refuse to check the token or rewrite everything to a new library for working with tokens, which allows you to specify the time zone when checking the ‘exp’ parameter. ‘Python-jose’ and ‘PyJWT’ don’t provide this feature as far as I’ve been able to find.

The text was updated successfully, but these errors were encountered:

Thanks for going one step further and diving into things, it make it much easier on us.

This is interesting, I would have assumed we would have heard about this long before now, as if it’s a timezone issue there’s got to be more than 1 person experiencing the issue. I’ll try to reproduce this tonight. However, I have a few concerns. python-jose uses datetime.utcnow() which should give you a time that is in UTC (+0) regardless of your local time zone.

eg: I’m in EST (-5). My current local time is 3:35pm (15:35). Running datetime.utcnow() returns 8:35pm (20:34), which is what it currently is in +0. So it should always be returning the UTC time

Are you able to run the following on your computer, just as a sanity check:

This should show both local time and utc time.

I also see a thumbs up for this issue by @MoonOfTheWind, are you exhibiting the same issue?

For me, it also seemed strange that these methods give out the time of my time zone, as we see on the screen, for some reason these two methods give me the same time. I’ll dig into the datetime library and maybe find something. But this is very strange.

Very strange, tm_isdst has a different value between the two commands, I wonder if that has anything to do with it.

Heres a couple more commands:

Should print out what python interprets as the time zone (perhaps python is seeing a TZ that is different from your system time?)

Should print out, well, tz name.

I hate dealing with time issues :/


Thanks for taking the time to help debug this, it’s very helpful.

So python is showing that your local time is UTC, without any timezone offset.

Can you attempt to login again, and step through the code to print out the following:

exp value on the JWT
now variable inside python-jose
leeway variable inside python-jose

Basically what are the values associated with your runtime when you exhibit this issue? That would be helpful to have 🙂

Also, which linux distro are you using? nvm, just noticed you mentioned it as 5.16.2-arch1-1 in the OP. Can you print out your python package versioning information (I think pip freeze might do it but I’m not 100%)

Sorry for the late reply, been very busy
I’m use venv.
pip freeze:

  • appdirs==1.4.4
  • attrs==21.4.0
  • beautifulsoup4==4.10.0
  • cattrs==1.10.0
  • certifi==2021.10.8
  • cffi==1.15.0
  • charset-normalizer==2.0.11
  • cryptography==36.0.1
  • cycler==0.11.0
  • ecdsa==0.17.0
  • future==0.18.2
  • idna==3.3
  • kiwisolver==1.3.2
  • Logbook==1.5.3
  • markdown2==2.4.2
  • matplotlib==3.2.2
  • numpy==1.19.2
  • packaging==21.3
  • pathlib2==2.3.6
  • Pillow==9.0.0
  • pyasn1==0.4.8
  • pycparser==2.21
  • pyparsing==3.0.7
  • python-dateutil==2.8.2
  • python-jose==3.0.1
  • PyYAML==6.0
  • requests==2.27.1
  • requests-cache==0.8.1
  • roman==3.3
  • rsa==4.8
  • six==1.16.0
  • soupsieve==2.3.1
  • SQLAlchemy==1.3.23
  • typing_extensions==4.0.1
  • url-normalize==1.4.3
  • urllib3==1.26.8
  • wxPython==4.0.6

The exp parameter is in the token and there is nothing special about it, the screen can be seen a little higher up the branch, I don’t think it has any value. I can’t print the value directly from the library, but I have no doubt that the code inside the library works exactly the same as from the interpreter. I don’t think that something depends on you here, this is a specific bug that does not occur on all devices that depends on the datetime library, I think that if possible it is worth writing some kind of bug report for the developers responsible for this library, I think if you describe in detail problem, maybe they will come up with something and release a patch. It is also possible that this is the fault of those people who are responsible for the repositories of my distribution. But I’ll still be happy to answer some of your questions and provide information that I can.

Seems like all the proper packages and versions.

I’m aware you posted a screenshot of the exp , but you never posted what now evaluated to, only that «the library developers use the current time zone of my computer (+3:00)». I have no doubt you checked this value for accuracy, but I would like literal values if possible. I assume you’re familiar with the debugger as you’ve been able to get the JWT and help with troubleshooting; is it possible for you to set a breakpoint and let me know what now and exp are evaluating to? You can put a breakpoint on the jwt.decode() within pyfa’s source files, then «step-into» that function to get to the library’s code; from there you should be able to step into _validate_exp and then read what is evaluated for exp and now .

It seems that your python is doing something funky with timezones — your computer is supposedly set to +3, however python is showing +0, so I want to know what exactly is happening in this function.

For example, this is what mine looks like (my computer is set to UTC-5):

And for reference, human-readable times
now :

So, at least for me, it is evaluating correctly; unfortunately it’s super hard to give any sort of guidance when I can’t reproduce myself.

I can try to get an Arch distro up and running and see if it’s possible to reproduce on there. @DarkFenX you’re much more experienced when it comes to Linux, you have any knowledge about python running on linux having some timezone issues?

Источник

Usage Examples¶

Encoding & Decoding Tokens with HS256В¶

Encoding & Decoding Tokens with RS256 (RSA)В¶

RSA encoding and decoding require the cryptography module. See Cryptographic Dependencies (Optional) .

If your private key needs a passphrase, you need to pass in a PrivateKey object from cryptography .

If you are repeatedly encoding with the same private key, reusing the same RSAPrivateKey also has performance benefits because it avoids the CPU-intensive RSA_check_key primality test.

Reading the Claimset without Validation¶

If you wish to read the claimset of a JWT without performing validation of the signature or any of the registered claim names, you can set the verify_signature option to False .

Note: It is generally ill-advised to use this functionality unless you clearly understand what you are doing. Without digital signature information, the integrity or authenticity of the claimset cannot be trusted.

Some APIs require you to read a JWT header without validation. For example, in situations where the token issuer uses multiple keys and you have no way of knowing in advance which one of the issuer’s public keys or shared secrets to use for validation, the issuer may include an identifier for the key in the header.

Registered Claim Names¶

The JWT specification defines some registered claim names and defines how they should be used. PyJWT supports these registered claim names:

  • “exp” (Expiration Time) Claim
  • “nbf” (Not Before Time) Claim
  • “iss” (Issuer) Claim
  • “aud” (Audience) Claim
  • “iat” (Issued At) Claim

Expiration Time Claim (exp)В¶

You can pass the expiration time as a UTC UNIX timestamp (an int) or as a datetime, which will be converted into an int. For example:

Expiration time is automatically verified in jwt.decode() and raises jwt.ExpiredSignatureError if the expiration time is in the past:

Expiration time will be compared to the current UTC time (as given by timegm(datetime.now(tz=timezone.utc).utctimetuple()) ), so be sure to use a UTC timestamp or datetime in encoding.

You can turn off expiration time verification with the verify_exp parameter in the options argument.

PyJWT also supports the leeway part of the expiration time definition, which means you can validate a expiration time which is in the past but not very far. For example, if you have a JWT payload with a expiration time set to 30 seconds after creation but you know that sometimes you will process it after 30 seconds, you can set a leeway of 10 seconds in order to have some margin:

Instead of specifying the leeway as a number of seconds, a datetime.timedelta instance can be used. The last line in the example above is equivalent to:

Not Before Time Claim (nbf)В¶

The nbf claim works similarly to the exp claim above.

Issuer Claim (iss)В¶

If the issuer claim is incorrect, jwt.InvalidIssuerError will be raised.

Audience Claim (aud)В¶

In the general case, the “aud” value is an array of case- sensitive strings, each containing a StringOrURI value.

In the special case when the JWT has one audience, the “aud” value MAY be a single case-sensitive string containing a StringOrURI value.

If multiple audiences are accepted, the audience parameter for jwt.decode can also be an iterable

The interpretation of audience values is generally application specific. Use of this claim is OPTIONAL.

If the audience claim is incorrect, jwt.InvalidAudienceError will be raised.

Issued At Claim (iat)В¶

The iat (issued at) claim identifies the time at which the JWT was issued. This claim can be used to determine the age of the JWT. Its value MUST be a number containing a NumericDate value. Use of this claim is OPTIONAL.

If the iat claim is not a number, an jwt.InvalidIssuedAtError exception will be raised.

Requiring Presence of Claims¶

If you wish to require one or more claims to be present in the claimset, you can set the require parameter to include these claims.

Retrieve RSA signing keys from a JWKS endpoint¶

OIDC Login Flow¶

The following usage demonstrates an OIDC login flow using pyjwt. Further reading about the OIDC spec is recommended for implementers.

In particular, this demonstrates validation of the at_hash claim. This claim relies on data from outside of the the JWT for validation. Methods are provided which support computation and validation of this claim, but it is not built into pyjwt.

© Copyright 2015-2022, JosГ© Padilla Revision 0a99cc24 .

Источник

Welcome to today’s post.

I will be discussing how to troubleshoot issues when implementing and testing JWT authentication in a .NET Core Web API service.

In a previous post I showed how to implement and test JWT authentication within our .NET Core Web API service.

Most of the details on how I obtain the JWT token and how we setup postman requests are shown in our post on JWT implementation.

Build and run your Web API within visual studio.

The web API will run under localhost as a blank page.

Open the POSTMAN utility.

Create an HTTP POST request to your API token provider.

For example:

http://localhost/BookLoan.Identity.API/api/Users/Authenticate

Obtain the JWT token from the JSON response.

Create a HTTP GET request to your Web API service:

http://localhost/BookLoan.Catalog.API/api/Book/List

Add an Authorization key to the Headers collection containing the JWT token.

Hit SEND.

Depending on the following responses we act accordingly:

Issue: No authentication header populated in Request.Headers

Below we see an empty request header during debugging:

To fix this issue we will need to enable the JWT middleware by adding:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme). 

to ConfigureServices() in startup.cs.

Issue: 401 Unauthorized : WWW-Authenticate: Bearer

For this issue we have two possibilities:

  1. The token is invalid or expired.

In this case we generate a new JWT bearer token and pass it into the HTTP GET or POST request Header collection.

2. The authorization attribute is misconfigured.

We will get the above error when we declare our web API method as follows:

[HttpGet("api/[controller]/List")]
[Authorize]
public async Task<List<BookViewModel>> List()
{
…
}

To rectify the authentication problem, we declare the method as follows:

[HttpGet("api/[controller]/List")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public async Task<List<BookViewModel>> List()
{
…
}

Another resolution is to ensure that the issuer signing key set in the startup.cs method ConfigureServices() is converted from Base 64. This is mentioned in the next issue.

Issue: www-authenticate -> Bearer error=”invalid_token”, error_description=”The signature is invalid”

To resolve, we check we have set the issuer signing key:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(
       options =>
       {
       	options.TokenValidationParameters = new TokenValidationParameters
              {
              	ValidateIssuerSigningKey = true,
                     IssuerSigningKey = new SymmetricSecurityKey(
                     	Convert.FromBase64String(
                     	Configuration.GetSection("AppSettings:Secret").Value)), 
                     ValidateIssuer = false,
                     ValidateAudience = false
      		};
});

If we have used a string encoding different from our JWT identity provider then the token will be invalid.

Issue: www-authenticate ->Bearer error=”invalid_token”, error_description=”The token is expired”

With this error we know what the problem is: our token has expired.

In this case we just obtain a new access token by calling our authentication method on our identity service.

To debug and parse errors from HTTP responses in your C# code here are some handy tips:

Debug your client.SendAsync() or client.PostAsync() calls

Add breakpoints to your client.SendAsync() and  client.PostAsync() calls.

Add a watch for the property:

response.Headers.WwwAuthenticate.ToString()

Check the response result response.IsSuccessStatusCode

If response.IsSuccessStatusCode is false then parse out the error response and act accordingly.

The response string will be similar to:

"Bearer error="invalid_token", error_description="The token is expired""

Parsing out the error information can be achieved as follows:

if (response.IsSuccessStatusCode)
{
// process the results
		. . .
}
else
{
// process the error
       	string errorString = response.Headers.WwwAuthenticate.ToString().Replace("Bearer","");
       	if (!errorString.StartsWith("{") || !errorString.EndsWith("}"))
       		errorString = "{ " + errorString + " }";
errorString = errorString.Replace("=", ":");
ApiErrorResponse apiErrorResponse =
       		JsonConvert.DeserializeObject<ApiErrorResponse>(errorString);
throw new AppException(apiErrorResponse.error_description);
}

Issue: Getting the 404 error code ‘Not Found’

There are two possible causes for this issue:

Firstly, check the request URI and ensure that it calls an existing API method.

Next, check the startup code in the API service.

In the ConfigureServices(IServiceCollection services) method look for the code block that defines the  JWT authentication:

            .AddJwtBearer(x =>
            {
	…
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
                x.Audience = "http://localhost/";
                x.Authority = "http://localhost/";
            });

If the value for the Audience server (the client application server) specifies a server that is not identical to the server hosting the client application, then all Web API methods will be inaccessible to the client application. Alternatively, leaving out the Audience and setting ValidateAudience to false will not validate the server of the client application.

In a future post I will show how to utilize our JWT token within our Web API service.  

That’s all for this post.

I hope you have found this useful and informative.

Andrew Halil is a blogger, author and software developer with expertise of many areas in the information technology industry including full-stack web and native cloud based development, test driven development and Devops.


Post Views:
340

github vimalloc / flask-jwt-extended / tests / test_jwt_encode_decode.py View on Github external
def test_decode_invalid_jwt(self):
        with self.app.test_request_context():
            identity_claim = 'identity'
            # Verify underlying pyjwt expires verification works
            with self.assertRaises(jwt.ExpiredSignatureError):
                token_data = {
                    'exp': datetime.utcnow() - timedelta(minutes=5),
                }
                encoded_token = jwt.encode(token_data, 'secret', 'HS256').decode('utf-8')
                decode_jwt(encoded_token, 'secret', 'HS256',
                           csrf=False, identity_claim=identity_claim)

            # Missing jti
            with self.assertRaises(JWTDecodeError):

                token_data = {
                    'exp': datetime.utcnow() + timedelta(minutes=5),
                    identity_claim: 'banana',
                    'type': 'refresh'
                }
                encoded_token = jwt.encode(token_data, 'secret', 'HS256').decode('utf-8')
github blohinn / flask-restplus-full-todo-example-with-jwt / app / v1 / resources / auth.py View on Github external
_access_token = jwt.encode({'uid': refresh_token.user_id,
                                        'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=15),
                                        'iat': datetime.datetime.utcnow()},
                                       current_app.config['SECRET_KEY']).decode('utf-8')
            _refresh_token = jwt.encode({'uid': refresh_token.user_id,
                                         'exp': datetime.datetime.utcnow() + datetime.timedelta(days=30),
                                         'iat': datetime.datetime.utcnow()},
                                        current_app.config['SECRET_KEY']).decode('utf-8')

            refresh_token.refresh_token = _refresh_token
            db.session.add(refresh_token)
            db.session.commit()

            return {'access_token': _access_token, 'refresh_token': _refresh_token}, 200

        except jwt.ExpiredSignatureError as e:
            raise e
        except (jwt.DecodeError, jwt.InvalidTokenError)as e:
            raise e
        except:
            auth_ns.abort(401, 'Unknown token error')
github ismetacar / ertis / src / resources / security.py View on Github external
def validate_token(self, token, secret, verify):
        try:
            decoded = jwt.decode(token, key=secret, algorithms='HS256', verify=verify)

        except jwt.ExpiredSignatureError as e:
            raise ErtisError(
                status_code=401,
                err_msg="Provided token has expired",
                err_code="errors.tokenExpiredError",
                context={
                    'message': str(e)
                }
            )
        except Exception as e:
            raise ErtisError(
                status_code=401,
                err_msg="Provided token is invalid",
                err_code="errors.tokenIsInvalid",
                context={
                    'e': str(e)
                }
github matrix-org / synapse / synapse / rest / client / v1 / login.py View on Github external
def do_jwt_login(self, login_submission):
        token = login_submission.get("token", None)
        if token is None:
            raise LoginError(
                401, "Token field for JWT is missing",
                errcode=Codes.UNAUTHORIZED
            )

        import jwt
        from jwt.exceptions import InvalidTokenError

        try:
            payload = jwt.decode(token, self.jwt_secret, algorithms=[self.jwt_algorithm])
        except jwt.ExpiredSignatureError:
            raise LoginError(401, "JWT expired", errcode=Codes.UNAUTHORIZED)
        except InvalidTokenError:
            raise LoginError(401, "Invalid JWT", errcode=Codes.UNAUTHORIZED)

        user = payload.get("sub", None)
        if user is None:
            raise LoginError(401, "Invalid JWT", errcode=Codes.UNAUTHORIZED)

        user_id = UserID(user, self.hs.hostname).to_string()

        auth_handler = self.auth_handler
        registered_user_id = yield auth_handler.check_user_exists(user_id)
        if registered_user_id:
            device_id = login_submission.get("device_id")
            initial_display_name = login_submission.get("initial_device_display_name")
            device_id, access_token = yield self.registration_handler.register_device(

Понравилась статья? Поделить с друзьями:
  • Just cause 4 как изменить язык интерфейса
  • Just cause 2 ошибка при запуске приложения 0xc0000906
  • Just cause 2 ошибка 0x0000906
  • Just cause 2 выдает ошибку fatal directx error code 3
  • Just cause 2 steam api dll ошибка