Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

skiarsi's avatar

using sanctum for mobile applications

Hi everyone. I want to know if u guys have experience in make Android/IOS apps with laravel api with sanctum token authentication system, is it working fine or I should choose jwt? thanks

1 like
24 replies
JussiMannisto's avatar

It works.

Sanctum is more flexible than JWT because you can invalidate the tokens by deleting them on the back end, unlike JWTs.

1 like
skiarsi's avatar

so how is that? make 2 token short and long term and sending in front end apps? or check if user is authenticated in each requests?

1 like
skiarsi's avatar

@JussiMannisto So for authentication with front end with phone apps, because they working with headers you should pass Bearer in headers like :

fetch('https://api.example.com/protected-resource', {
        method: 'GET',
        headers: {
            'Authorization': 'Bearer YOUR_JWT_TOKEN_HERE',
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));

When you make long time token and short time also with sanctum, both will save on Database that frontend don't care about them so you should pass tokens to frontend and save it to secure local storage and pass them with every requests. my question is: how front end can undrestand user is Authenticated when we using sanctum but we working with Bearer. Or if U guys don't do this strategy (that is most common strategy on mobile apps) what you doing, how you handle auth on user requests? how client authorizing to access secure datas?

1 like
JussiMannisto's avatar

@skiarsi You authenticate the user by sending the bearer token with every API request, and the auth:sanctum middleware handles authentication. Here's a simple rundown of how you might handle authentication in a mobile app:

  1. The user signs in to the app using a username and password, SSO, or something else.
  2. The server generates a Sanctum token and sends it to the client.
  3. The token is stored securely on the device. For iOS, this means storing it in the Keychain. For Android, you must encrypt it before storing it (e.g. in SharedPreferences), while storing the encryption key in the Android Keystore.*
  4. When the user opens the app, you retrieve the token and include it with every request that goes to the server.

Token lifetime is its own topic. You might use a long-lived token that you silently refresh with an API call every time the app launches. Since Sanctum tokens can be revoked on the server, you don't need to implement a refresh/access token pattern like you might with JWTs: you can simply replace the token when needed.

You have to balance user convenience vs. security when it comes to token lifetimes. If the app is launched rarely and tokens time out, that can really annoy users as they have to keep signing in. You could have very long-lived or even infinite tokens, but in that case you should probably provide some mechanism for revoking them, e.g. a "Sign out from other devices" feature.

* Fun fact, Google recently deprecated the entire androidx.security:security-crypto library. That means you can no longer use its EncryptedSharedPreferences, and you have to either implement encryption yourself or use a 3rd party library.

how front end can undrestand user is Authenticated when we using sanctum but we working with Bearer

Whenever the client sends a request to an API, it receives a response. The response status code indicates whether the request was successful: 200 or 201 means success, 403 means authorization failed, etc. This is also how the fetch API call in your code example knows if the request was a success.

If user authentication fails, you'll receive a 401 response.

2 likes
tuncdogu55's avatar

I guess you meaning "auth:sanctum" middleware for authentication of every request, you can use like this :

use Illuminate\Http\Request;

Route::get('/user', function (Request $request) { return $request->user(); })->middleware('auth:sanctum');

or if you want to read more you can check this: https://laravel.com/docs/12.x/sanctum#spa-authentication

1 like
skiarsi's avatar

@tuncdogu55 It's for web apps authentication, you should not using this strategy on mobile apps, mobile apps know headers and working with Bearer on request

1 like
JussiMannisto's avatar

@skiarsi That works perfectly fine on mobile apps. The auth:sanctum middleware checks the bearer token and uses it for authentication.

1 like
jlrdw's avatar

@skiarsi another to look at is OpenID Connect. I have only read about it so far, but Google uses it, so it must be pretty darn good. But I agree with @martinbean I would choose passport over sanctum.

2 likes
JussiMannisto's avatar

@jlrdw OIDC works on top of OAuth 2. My question is: why would you implement an entire identity provider if all you're looking for is an authentication method for your own app?

1 like
JussiMannisto's avatar

@martinbean I think OAuth is an unnecessary complication if you just want authentication for your own app. Sanctum is more straightforward.

1 like
JussiMannisto's avatar

@vincent15000 There's not really anything to explain. If you think Sanctum is less secure, maybe you could elaborate on how that is?

1 like
JussiMannisto's avatar

@vincent15000 That sentence doesn't explain anything.

Passport isn't more secure than Sanctum. It's OAuth2 compliant, but very few Laravel apps need that for anything.

I'm going to stop replying now. If you're wondering if you should use Passport for mobile app authentication, you can read the first section from Passport's docs:

If your application absolutely needs to support OAuth2, then you should use Laravel Passport.

However, if you are attempting to authenticate a single-page application, mobile application, or issue API tokens, you should use Laravel Sanctum. Laravel Sanctum does not support OAuth2; however, it provides a much simpler API authentication development experience.

And here's what Taylor has said on the subject:

https://youtu.be/DMNsW-3ekR0?feature=shared&t=466

1 like
vincent15000's avatar

@JussiMannisto I don't say that you should use Passport for mobile app, Sanctum is also a good choice.

But if you have a public API, OAuth is IMHO a better choice.

Public doesn't mean mobile app.

martinbean's avatar

@JussiMannisto Laravel and its creator suggest using its own, first-party package over an established and widely-used protocol?

Mild shock

2 likes

Please or to participate in this conversation.