3

I have an issue with my current projet. I have been using Symfony 2.6 this project is an API called by my front-end. The authentication and log in flow is very specific it uses a middleware (other website).

I add a bundle called JWTAuthenticationWebToken So I need to manually log in user due to the use of a middleware. I installed correctly the bundle and add the right settings but this custom user provider is never called.

How to implements it with the manual login ?

My controller:

<?php $token = new UsernamePasswordToken($user, null, "login", $user->getRoles());
            $this->get("security.context")->setToken($token); //now the user is logged in
            //now dispatch the login event
            $request = $this->get("request");
            $event = new InteractiveLoginEvent($request, $token);
            $this->get("event_dispatcher")->dispatch("security.interactive_login", $event); ?>

security.yml

firewalls:
    # disables authentication for assets and the profiler, adapt it according to your needs
    dev:
        pattern:  ^/(_(profiler|wdt)|css|images|js)/
        security: false
    # the login page has to be accessible for everybody
    demo_login:
        pattern:  ^/demo/secured/login$
        security: false
    login:
        pattern:   /api/user/uber/f6d75c949cda2517b826cacba5523792
        stateless: true
        anonymous: true
        form_login:
            check_path:               /api/user/uber/f6d75c949cda2517b826cacba5523792
            success_handler:          lexik_jwt_authentication.handler.authentication_success
            failure_handler:          lexik_jwt_authentication.handler.authentication_failure
            require_previous_session: false

    api:
        pattern:   ^/(api)
        stateless: true
        lexik_jwt: ~   

I also wrote the two files "ApiKeyAuthenticator" and "ApiKeyUserProvider" as mentionned here for manual auth. http://symfony.com/doc/current/cookbook/security/api_key_authentication.html

EDIT : I also created the listeners mentionned in LexikJWTAuthenticationBundle doc'

what's wrong ? :(

Thanks for your help

2
  • What is wrong? Too many possible failure points to make even a wild guess. I would suggest making a new Symfony project and add only the lexik bundle. Then step through the documentation and get the default configuration working. Only then try to customize with your manual login which probably is not even needed. Commented Apr 21, 2015 at 13:17
  • That's the entire content of your security.yml? Don't you have any Entity Provider configured? Why you need to manually log in your user? The point of using the LexikJWTAuthenticationBundle is to let the bundle handle the authentication in a way it would be transparent for your controllers. Commented Jul 2, 2015 at 21:10

1 Answer 1

2

After a lot of search (google, stackoverflow, sample applications, bundle's doc , ...), it seems that there was no proposed solution to authenticate users manually from a controller.

Also, I had to open the source code, find which method is called to generate the token on successful authentication event (source code), and finally adapt the code to my need (Register/Login user to the API from the response of a Facebook login, in a mobile application).

My alternative :

// SecurityController.php

protected function generateToken($user, $statusCode = 200)
{
    // Call jwt_manager service & create the token
    $token = $this->get('lexik_jwt_authentication.jwt_manager')->create($user);

    // If you want, add some user informations
    $userInformations = array(
        'id'         => $user->getId(),
        'username'   => $user->getUsername(),
        'email'      => $user->getEmail(),
        'roles'      => $user->getRoles(),
    );

    // Build your response
    $response = array(
        'token' => $token,
        'user'  => $user,   
    );

    // Return the response in JSON format
    return new JsonResponse($response, $statusCode);
}

The token will be returned same as the classic login_check handler, and have the same time before expiration.

Hope this help for next users.

Sign up to request clarification or add additional context in comments.

6 Comments

Interesting .. Using LexikJWTAuthenticationBundle, I have "onAuthenticationSuccessResponse" listener and a specific controller action having barely the same code logic. Does anyone know if there is a way to call my controller's action from inside this listener and then push its return JsonResponse datas into the AuthenticationSuccessEvent event datas ? I hope this makes sense :/. Thank you.
Hi @Stphane, since this question I worked a lot on LexikJWTAuthenticationBundle and now I'm the main maintainer of it. Seeing this answer feels wrong to me, except for very specific needs (e.g. authenticate user from an endpoint that is browsed via a link from a registration confirm email). Otherwise, only configuration should be needed, as shown in the documentation. Why did you reproduced this in an AuthenticationSuccessEvent listener? LexikJWTAuthentication provides a builtin AuthenticationSuccess event and handler, returning a response containing a token, that just need to be configured.
I did not reproduce this answer in the …sucessListener actually. I found this SO while looking for a way to achieve what I mentioned in my first comment. That's good news you're the maintainer! You might be able to help me find my way! I've set a route to serve datas requested from a mobile app. Upon login, users get their token, but I needed to append those former datas to save my users another ajax request right after. I need a way to make listener and controller's action share some code instead of having it coded twice in 2 differents places. What would you suggest? Thank you :)
LexikJWTAuthenticationBundle only does Form Logins, I had to put all the variables in the JWTTokenAuthenticator on protected and override almost everything to get it to work properly without a Form. Honestly, all I wanted was to generate a token but that took almost a week of digging through code and manually breaking up the code to do.
@G_V If your need was to generate the token from a controller, I really don't see how extending/changing the JWTTokenAuthenticator could help. Just using the lexik_jwt_authentication.jwt_manager as shown here works well for generating an user. Could you please give me more details about what you wanted to achieve? It would help to improve UX in the bundle itself.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.