I create a spring MVC application that uses spring security for authentication, here's the spring-security.xml
<http use-expressions="true">
<form-login login-page="/homepage.jsp" default-target-url="/homepage.jsp" authentication-failure-url="/homepage.jsp?login-success=false" />
<logout logout-success-url="/homepage.jsp" />
</http>
<authentication-manager alias="authenticationManager" >
<authentication-provider>
<password-encoder hash="sha" />
<jdbc-user-service data-source-ref="marketDataSource"
users-by-username-query="
select email_address, password, '1'
from user where email_address=?"
authorities-by-username-query="
select email_address, 'ROLE_USER' from user
where email_address=?"
/>
</authentication-provider>
</authentication-manager>
when a new user try to register, he fill in registration from and press submit, that will create a new user, if the registration successfully completed, I try to authenticate the registered user using this method:
private void authenticateUserAndSetSession(User user, HttpServletRequest request) {
List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
grantedAuthorities.add(new GrantedAuthorityImpl("ROLE_USER"));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
user.getEmailAddress(), user.getPasswordSha(), grantedAuthorities);
request.getSession();
token.setDetails(new WebAuthenticationDetails(request));
try {
Authentication authenticatedUser = authenticationManager
.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
} catch (Exception e) {
e.printStackTrace();
}
}
I checked this post Auto login after successful registration to make the previous method, but when I try to use it, it throws Bad Credential Exception, what's wrong with this solution?
I had been faced with the similar problem. In legacy code the password was hashed by hand.
The better choice is to store object of User class (may be it is a plain form binding) with the plain password and clear it later. Clearing credencials is the responsibility of spring-security too (interface
org.springframework.security.core.CredentialsContainer). If it isn't possible remove tag of encoder or use the plain text encoder<password-encoder hash="plaintext"/>.