Skip to content

Commit 8b42b11

Browse files
lonnieezellkenjis
authored andcommitted
Added mobile auth guide.
1 parent e2b4935 commit 8b42b11

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

docs/guides/mobile-apps.md

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# Mobile Authentication with Access Tokens
2+
3+
Access Tokens can be used to authenticate mobile applications that are consuming your API. This is similar to how you would work with [third-party users](api-tokens.md) of your API, but with small differences in how you would issue the tokens.
4+
5+
## Issuing the Tokens
6+
7+
Typically, a mobile application would issue a request from their login screen, passing in the credentials to authenticate with. Once authenticated you would return the `raw token` within the response and that would be saved on the device to use in following API calls.
8+
9+
Start by creating a route that would handle the request from the login screen on the mobile device. The device name can be any arbitrary string, but is typically used to identify the device the request is being made from, like "Johns iPhone 13".
10+
11+
```php
12+
13+
// Routes.php
14+
$route->post('auth/token', 'App\Controllers\Auth\LoginController::mobileLogin');
15+
16+
// LoginController.php
17+
namespace App\Controllers\Auth;
18+
19+
use CodeIgniter\Controllers\BaseController;
20+
21+
class LoginController extends BaseController
22+
{
23+
public function mobileLogin()
24+
{
25+
// Valide credentials
26+
$rules = setting('Validation.login') ?? [
27+
'email' => [
28+
'label' => 'Auth.email',
29+
'rules' => config('AuthSession')->emailValidationRules,
30+
],
31+
'password' => [
32+
'label' => 'Auth.password',
33+
'rules' => 'required',
34+
],
35+
];
36+
37+
if (! $this->validate($rules)) {
38+
return $this->response
39+
->setJSON(['errors' => $this->validator->getErrors()])
40+
->setStatusCode(422)
41+
}
42+
43+
// Attempt to login
44+
$result = auth()->attempt($this->request->getPost(setting('Auth.validFields')));
45+
if (! $result->isOK()) {
46+
return $this->response
47+
->setJSON(['error' => $result->reason])
48+
->setStatusCode(401);
49+
}
50+
51+
// Generate token and return to client
52+
$token = auth()->user()->generateAccessToken(request()->getVar('device_name'));
53+
54+
return $this->response
55+
->setJSON(['token' => $token->raw_token]);
56+
}
57+
}
58+
```
59+
60+
When making all future requests to the API, the mobile client should return the raw token in the `Authorization` header as a `Bearer` token.

0 commit comments

Comments
 (0)