rest – Should I return user data in an authentication endpoint using JWT?

Yes/No.

End points are functions. From this perspective it doesn’t matter what they do as long as the client is aware that this is what will happen, and is happy to deal with the output/outcomes.

So if you write the only client and you have a sequence of six operations that are called in a row, it might make sense to collapse them down into a single call that does it all.

But if you don’t write the only client, then there is a good chance that such complex endpoints will make life harder for them. It would be like trying to get a paper and having to verify that you have medical insurance. Its better to have smaller concise operations to allow these other clients to pick and choose how and when.

A middle ground is to offer a small variety of common chains by opt in.

  • /auth -> just the JWT token
  • /auth?include=user -> JWT token + user details please

As for REST, then yes it matters a lot.

The two graces of REST are that the server doesn’t have to keep connection state, and that intermediaries can cache the result to distribute to their audience to reduce overall load on the server.

JWT tokens don’t fit in this model. You don’t want them cached, you don’t want them shared.

Other data though might be perfectly fine to cache. Perhaps not confidential user data, but if those details were public user information it would be fine.

Mixing the two types eliminates one of the benefits from a REST system. Not the end of the world, but if you are trying to get the scalability it is an anti-pattern.

typescript – Angular10 RxJS – Interceptor to add/refresh JWT Token

I have a project, for which I use Tokenauthentication with JWT Tokens. I am relatively new to Angular Development and rxjs in particular, so there are a lot of concepts I am likely not yet familiar with or can’t apply properly. My Backend is Django 3, using the Django Rest Framework and rest_framework_simplejwt.

What the interceptor is doing is check any outgoing HTTP request on if it’s a call to my API. If it is, attach the JWT Token. If it is and the Access Token is expired, refresh the Access Token first, then send the call to the API. I haven’t yet coded in the scenario on what to do if the Refresh Token expires/is close to expiring but I’m doing this step by step and that’s next on the list.

I don’t like my code here. It’s hard for me to grasp to the point I need comments to make it easier. An even bigger problem is that I don’t fully understand the code and thus am struggling to split the intercept function into smaller chunks to move into their own functions.

What could I be doing to make it more comprehensible? What could I “split off” into some nicely named function?

Here the code:

//jwt-interceptor.ts
@Injectable()
export class JWTInterceptor implements HttpInterceptor{
    private tokenRefreshInProgress: boolean = false;
    private refreshAccessTokenSubject: Subject<any> = new BehaviorSubject<any>(null);

    constructor(private userService: UserService){}

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>{
        if (this.isApiUrl(request.url)){
            const accessToken = this.userService.getAccessToken();

            //Below: If Access Token Expired and no refresh of it currently running
            if(this.userService.isTokenExpired(accessToken) && !this.tokenRefreshInProgress){
                this.tokenRefreshInProgress = true;
                this.refreshAccessTokenSubject.next(null);

                return this.userService.refreshToken().pipe(
                    switchMap(authResponse => {
                        this.userService.setAccessToken(authResponse.access);

                        this.tokenRefreshInProgress = false;
                        this.refreshAccessTokenSubject.next(authResponse.access);
                        request = this.addTokenToRequest(authResponse.access, request);
                        return next.handle(request);
                    })
                )

            //Below: If Access Token is expired and a refresh of it already running
            } else if(this.userService.isTokenExpired(accessToken) && this.tokenRefreshInProgress){
                return this.refreshAccessTokenSubject.pipe(
                    filter(result => result !== null),
                    first(),
                    switchMap(response => {
                        request = this.addTokenToRequest(this.userService.getAccessToken(), request);
                        return next.handle(request);
                    })
                )
            
             //Below: If Access Token Valid
            } else {
                request = this.addTokenToRequest(accessToken, request);      
            }      
        } 

        return next.handle(request);
    }

    isApiUrl(url: string): boolean{
        const isApiUrl: boolean = url.startsWith(Constants.wikiApiUrl);
        const isTokenLoginUrl: boolean = url.endsWith('/token');
        const isTokenRefreshUrl: boolean = url.endsWith('/token/refresh');
        return isApiUrl && !isTokenLoginUrl && !isTokenRefreshUrl;
    }

    addTokenToRequest(token: string, request: HttpRequest<any>): HttpRequest<any>{
        const httpHeaders = new HttpHeaders().set("Authorization", `Bearer ${token}`);
        request = request.clone({headers: httpHeaders});
        return request;   
    }
}

//methods from UserService class in user.service.ts
  isTokenExpired(token: string): boolean{
    const (encodedHeader, encodedPayload, encodedSignature) = token.split('.');
    const payload = JSON.parse(atob(encodedPayload));
    const expiryTimestamp = payload.exp;
    const currentTimestamp = Math.floor((new Date).getTime()/1000);
    return currentTimestamp >= expiryTimestamp;
  }

  getRefreshToken(): string{
    return localStorage.getItem('refresh_token');
  }

  getAccessToken(): string{
    return localStorage.getItem('access_token');
  }

  setAccessToken(accessToken: string): void{
    localStorage.setItem('access_token', accessToken);
  }

  refreshToken(): Observable<{access: string, refresh: string}>{
    const refreshToken = this.getRefreshToken();
    return this.http.post<{access, refresh}>(Constants.wikiTokenRefreshUrl, {refresh: refreshToken});
  }
```

authorization – What identity and/or access data are JWT claims intended for?

I am an application developer and am building a token-based auth mechanism for my application. Essentially, the user will log in with username+password, if the credentials are valid, my code will generate a JWT (probably going with a 30-minute expiry, at least to start with).

If they attempt to request authenticated resources, they will need the JWT stored as a bearer token in their HTTP auth header. When this happens, I’ll verify/validate the JWT, and if its good, give them access.

Right now I’m struggling with a particular aspect of the design here and I was wondering what the security best practices dictate in such a situation, and that is: what information can/should I put as “claims” on my JWTs?

I guess to start with, I’m not entirely sure what the underlying intent of a JWT claim is, which might help point me in the right direction.

But basically, with respect to my authorization scheme, I’m wondering if it is a good practice (or not) to not only place something in the JWT that identifies the requester as a principal in the system (identification), but also to place claims on that token regarding access control; meaning, do I put a list of all my user’s roles, ACLs, etc. on a JWT claim?

Beyond authorization-related data, what other information do you typically see (correctly) added to a JWT in the form of claims? Thanks in advance for any and all help!

Do JWT refresh tokens have security benefits?

I’m trying to figure out where the security benefits of having a refresh token and an access token for JWT are.

Another post on stackexchange says:

But why is it safe to have a refresh token that can last for months
when the JWT can’t? The answer is simple: It must be possible to
revoke the refresh token so that the server no longer accepts it and
won’t issue new JWTs to someone who has it.

  1. Imagine someone has your refresh token -> You have to revoke the refresh token

  2. Imagine you have no refresh token, but just grant the access token with long lifetime -> You have to revoke the access token.

In both cases, you have to revoke one token.

Why can you not just revoke an access token and not have a refresh token?

Is that possible to update JWT Token secret without logging out every user?

I am using a JWT token implementation of this https://jwt-auth.readthedocs.io/en/develop/quick-start/

I need to update the secret key and is there a way to update it without logging out every user? I presume it’s not possible to reuse the old token once my secret key is changed. So all my users will be logged off and need to log in again. Is there any way to go around this?

If not, if for security reason, I need to update the secret monthly, that will be pretty troublesome to ask my user to re-login monthly.

javascript – How OAuth sends jwt with information about the user?

Help please, what method uses OAuth to transfer jwt with user information to the final website (client)?

Unfortunately, jwt cannot be passed to the client via localStorage or cookies as the domains are different.

postMessage doesn’t seem to work either, since all actions are performed in one tab without opening new tabs (pages).

c# – Where to carry JWT Tokens in Requests

I have an AspNet application which I’m authenticating using a separate AspNet Core application. It returns a JWT token which is then carried in a Http Cookie. The AspNet application validates each request has a valid JWT Token.

The immediate issue I face is the 4kb limit of HTTP Cookies. I need to carry permission information in the Token Claims which might exceed this limit.

I’ve thought about a couple of paths to solve this and would like advice:

  1. Compressing the token – however I noticed the compression rates aren’t consistent.

  2. Switching to Http Header with a 16kb limit in IIS – I’m not sure yet how to set it from the AspnetCore side and I guess I’ll need to set them on each request from the Client as they aren’t persisted like Cookies.

  3. Store it in the Http Body and set it on each request from the Client.

Are there any other considerations which would be helpful here?

What is the impact of an exposed secret key for a JWT token implementation?

I am currently using JWT implementation for the authentication part of my APIs. https://jwt-auth.readthedocs.io/en/develop/

A private key is used to sign the token generated and used to make sure it’s not tempered with when it’s used later for other API.

My question is – What is the impact if this private key is leaked? What can the bad guy do with it?
https://blog.pentesteracademy.com/hacking-jwt-tokens-leaked-jwt-secret-578955645a04
From here, my understanding is that the payload can be altered. Hence, in that example, a normal user can be changed to admin. But in my scenario, I dont have any other important fields except expiration date.

image

So other that the bad guy able to forever extend his own token expiry date, what are other impact that I am facing?

Thanks!

node.js – NestJS – how to check if JWT can access specific endpoint

Let’s say I have 3 endpoints: A is for generating JWT token, B for accessing data of user X and C for accessing data of user Y. Now, what I want to do is, that I can from recieved token somehow in controller guards figure out, if user can access endpoint.
So, token generated for user X can only access endpoint B, token generated for user Y can only access endpoint C.
Token has to be generated at endpoint A, since users sign in at same form.
If question is unclear ask in comment.

authentication – Magic links: JWT vs random string

Would it not be more prudent to just generate a large (like 50 chars), unique, random, alphanumeric string (let’s call it LURA) then store it, the email and the date and send it to the user? When the verification endpoints get hit, we can say, “yepp, I have that thing on file and I issued it 2 minutes ago, in you go”. The purpose of using JWT would be to verify that I was the one who created the token (with my key), but I can also verify that if I just see if I have the LURA string on file, right? Also, JWT has problems. I have a feeling JWT was intended to be used when the machine that’s validating it is different then the one issuing it and that its use is detrimental to security in this case.