Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically login as a user using Spring Security without knowing their password?

My application uses Spring Security, and my client requires:

  • users to be able to automatically login after signup.
  • an admin to login as any user without knowing their password.

So I need to figure out how to login as any user automatically without knowing their password.

How can this be accomplished using Spring Security?

like image 415
Brad Parks Avatar asked Aug 21 '12 14:08

Brad Parks


2 Answers

for second problem

an admin to login as any user without knowing their password.

you should use switch user feature from spring. javadoc and article

like image 34
Jigar Parekh Avatar answered Oct 10 '22 15:10

Jigar Parekh


To get this to work, I had to:

Configure a reference to the UserDetailsService (jdbcUserService)

<authentication-manager>
<authentication-provider>
<jdbc-user-service id="jdbcUserService" data-source-ref="dataSource"
  users-by-username-query="select username,password, enabled from users where username=?" 
  authorities-by-username-query="select u.username, ur.authority from users u, user_roles ur where u.user_id = ur.user_id and u.username =?  " 
/>
</authentication-provider>
</authentication-manager>

Autowire my userDetailsManager in my controller:

@Autowired
@Qualifier("jdbcUserService")  // <-- this references the bean id
public UserDetailsManager userDetailsManager;

In the same controller, authenticate my user like so:

@RequestMapping("/automatic/login/test")
public @ResponseBody String automaticLoginTest(HttpServletRequest request) 
{
    String username = "[email protected]";

    Boolean result = authenticateUserAndInitializeSessionByUsername(username, userDetailsManager, request);

    return result.toString();
}

public boolean authenticateUserAndInitializeSessionByUsername(String username, UserDetailsManager userDetailsManager, HttpServletRequest request)
{
    boolean result = true;

    try
    {
        // generate session if one doesn't exist
        request.getSession();

        // Authenticate the user
        UserDetails user = userDetailsManager.loadUserByUsername(username);
        Authentication auth = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(auth);
    }
    catch (Exception e)
    {
      System.out.println(e.getMessage());

      result = false;
    }

    return result;
}

Note that a good precursor to just using spring security for your app can be found here.

like image 122
Brad Parks Avatar answered Oct 10 '22 16:10

Brad Parks