My application uses Spring Security, and my client requires:
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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With