Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to login user from java code in Spring Security?

I am trying to write some script in my java code, where i need to login users, do some stuff like real user could do from web client and logout for each of them.

How does this work in spring security? What should i do? I mean how to imitate user authentication like in real, with session, roles and authorities?

Thanks a lot!

like image 564
DamienMiheev Avatar asked Jun 26 '26 15:06

DamienMiheev


1 Answers

Few time later i found solution:

@Component
public class AuthorityUtils {

//org.springframework.security.authentication.AuthenticationManager
@Autowired
private AuthenticationManager authenticationManager;

public void loginDirectly(String email, String password) {
    UsernamePasswordAuthenticationToken loginToken = new UsernamePasswordAuthenticationToken(email, password);
    Authentication authenticatedUser = authenticationManager.authenticate(loginToken);
    SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
    }
}
like image 190
DamienMiheev Avatar answered Jun 28 '26 06:06

DamienMiheev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!