Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JWTAuth authentication with username instead of email

Is there any way to use in laravel jwt-auth the authentication using username (or any custom column), instead of an email?

This is the existing code

public function authenticate(Request $request)
{
    $credentials = $request->only('email', 'password');

    try {
        // verify the credentials and create a token for the user
        if (! $token = JWTAuth::attempt($credentials)) {
            return response()->json(['error' => 'invalid_credentials'], 401);
        }
    } catch (JWTException $e) {
        // something went wrong
        return response()->json(['error' => 'could_not_create_token'], 500);
    }

    // if no errors are encountered we can return a JWT
    return response()->json(compact('token'));
}

I want to do Something like this

$credentials = $request->only('username', 'password');

One way is to put usernames in email column but that is a bad solution.

like image 569
Jamshad Ahmad Avatar asked Apr 06 '16 11:04

Jamshad Ahmad


2 Answers

I've found a way here

We can grab a user from model (on the base of custom fields) like

// grab some user

$user = User::first();

and authenticate it manually.

$token = JWTAuth::fromUser($user);
like image 145
Jamshad Ahmad Avatar answered Sep 21 '22 23:09

Jamshad Ahmad


Looking around, it looks like it is possible to do this by setting the credentials like so $credentials = $request->only('username', 'password');.

So all up it would look like this:

public function authenticate(Request $request)
    {
        // grab credentials from the request
        //$credentials = $request->only('email', 'password');
        // Change email to username
        $credentials = $request->only('username', 'password');

        try {
            // attempt to verify the credentials and create a token for the user
            if (! $token = JWTAuth::attempt($credentials)) {
                return response()->json(['error' => 'invalid_credentials'], 401);
            }
        } catch (JWTException $e) {
            // something went wrong whilst attempting to encode the token
            return response()->json(['error' => 'could_not_create_token'], 500);
        }

        // all good so return the token
        return response()->json(compact('token'));
    }
like image 35
James Avatar answered Sep 17 '22 23:09

James