-->

Custom Authentication which doesn't need UserP

2019-04-02 00:08发布

问题:

I looked for a solution on the web for my configuration but I can't find something which satisfies my needs. So far, I have been working on this for 3 full days, and I can't make it works properly, I am sure there are several things that I didn't understand.

I am developing my symfony application on the branch 2.1.

To make this short. I have a webservice which I want to use for the authentication.

This is the flow I want to implement:

  1. User submits credentials
  2. These credentials (username & password needed) are sent to my webservice
  3. If the username/password are correct, the webservice give an array with Username, Roles, and some others things but the password. (if the credentials are not correct, an array with one field will be return)
  4. As soon as the webservice gives the "big" array, I want the user to be considered as authenticated.
  5. In function of the roles returned, I want the Symfony security component gives the corresponding authorization to the user.
  6. I would like to avoid to make a call to the webservice for each page browsed.

I don't know if it is possible to make this using Symfony, for sure this workflow seems not to be the more secure, but I can't see another way for using this webservice.

To finish, I don't need to have a UserProvider since my authentication is made on the remote service. But apparently, Symfony components requires an user provider (doen't matter its type).

I thank you in advance

Edit: To make it simpler, is it possible to pass something more than just the variable $username in loadUserByUsername() function in the UserProvider class (which implements UserProviderInterface)? I need to have the user pass in addition to his/her username to retrieve the User Object.

回答1:

The AuthenticationProvider will normally call UserProvider.loadUserByUsername. In your case, there is no need to call it. Your authenticate method can take care of creating the user and passing back the token.

The authenticated token eventually ends up in the session.

The problem is that by default, when the next request comes in, the system will retrieve the token/user from the session and then call UserProvider.refreshUser($user) which, again by default, reloads the user with loadUserByUsername.

So you need to create your own user provider and just have refreshUser return the same user. You will need a loadUserByUsername just to satisfy the interface but it should never be called.

If you do want to periodically refresh your user from the web service then you will need to add in your own listener to load the token in from the session and override the default behavior.