Created
July 18, 2012 15:45
-
-
Save muanis/3137040 to your computer and use it in GitHub Desktop.
Custom validation on Spring security
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* the filter */ | |
public class MyAuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter { | |
@Autowired | |
private transient Validator validator; | |
protected MyAuthenticationProcessingFilter(String defaultFilterProcessesUrl) { | |
super(defaultFilterProcessesUrl); | |
} | |
@Override | |
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { | |
LoginForm loginForm = new LoginForm(); | |
loginForm.setUsername(request.getParameter("username")); | |
loginForm.setPassword(request.getParameter("password")); | |
Errors errors = new BeanPropertyBindingResult(loginForm, "login"); | |
if(!this.isValid(validator, errors, loginForm)) { | |
throw new AuthenticationRequiredFieldsException("validation failed",errors); | |
} | |
MyAuthentication myAuthentication = new MyAuthentication(loginForm.getUsername(), loginForm.getPassword()); | |
Authentication authResult = this.getAuthenticationManager().authenticate(myAuthentication); | |
return authResult; | |
} | |
public class AuthenticationRequiredFieldsException extends AuthenticationException { | |
private static final long serialVersionUID = -3613393016881542212L; | |
private Errors errors; | |
public AuthenticationRequiredFieldsException(String msg, Throwable error) { | |
super(msg, error); | |
} | |
public AuthenticationRequiredFieldsException(String msg) { | |
super(msg); | |
} | |
public AuthenticationRequiredFieldsException(String msg, Errors errors) { | |
super(msg); | |
this.errors = errors; | |
} | |
public Errors getErrors() { | |
return errors; | |
} | |
} | |
public class LoginForm { | |
@NotEmpty | |
@Length(min=5,max=30) | |
private String username; | |
@NotEmpty | |
@Length(min=5,max=60) | |
private String password; | |
public String getUsername() { | |
return username; | |
} | |
public void setUsername(String username) { | |
this.username = username; | |
} | |
public String getPassword() { | |
return password; | |
} | |
public void setPassword(String password) { | |
this.password = password; | |
} | |
} | |
} | |
/** then using on the jsp that prints the login form: | |
<form:form commandName="login"> | |
<form:errors path="*" cssClass="error"></form:errors> | |
</form:form> | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment