Skip to content

Instantly share code, notes, and snippets.

@muanis
Created July 18, 2012 15:45
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muanis/3137040 to your computer and use it in GitHub Desktop.
Save muanis/3137040 to your computer and use it in GitHub Desktop.
Custom validation on Spring security
/* 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