How to make extra validation in Spring Security login form?

后端 未结 3 1222
谎友^
谎友^ 2021-01-01 06:04

I wonder how to make extra validation on login form before it will be processed by Spring Security. I\'m thinking about some LoginController, LoginForm bean, but i don\'t kn

相关标签:
3条回答
  • 2021-01-01 06:48
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView signInPage(
                        @RequestParam(value = "error", required = false) String error,
                        @RequestParam(value = "logout", required = false) String logout) 
    {
        ModelAndView mav = new ModelAndView();
        //Initially when you hit on login url then error and logout both null
        if (error != null) {
            mav.addObject("error", "Invalid username and password!");
        }
    
        if (logout != null) {
            mav.addObject("msg", "You've been logged out successfully.");
        }
        mav.setViewName("login/login.jsp");
    }
    

    Now if in case login become uncessful then it will again hit this URL with error append in its URL as in spring security file you set the failure URL. Spring security file:

    <security:form-login
        authentication-failure-url="/login?error=1"
    />
    

    Then your URL becomes url/login?error=1. Then automatically signInPage method will call and with some error value. Now error is not null and you can set any string corresponding to url and we can show on jsp using these following tags:

    <c:if test="${not empty error}">
        <div class="error">${error}</div>
    </c:if>
    
    0 讨论(0)
  • 2021-01-01 06:49

    You could subclass UsernamePasswordAuthenticationFilter:

    http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilter.html

    You could override the attemptAuthentication() method, have it call super.attemptAuthentication(), and if that returns a non-null Authentication object, perform your additional work (to see if the user checked the box).

    http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilter.html#attemptAuthentication(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)

    The docs for how to specify your customer filter are here:

    http://static.springsource.org/spring-security/site/docs/3.0.x/reference/ns-config.html#ns-custom-filters

    0 讨论(0)
  • 2021-01-01 07:05

    Just adding more information on top of @sdouglass comment.

    On the filter you'll not have access to the form for binding purposes.

    I managed to get it with default validation by doing the following.

    https://gist.github.com/3137040

    0 讨论(0)
提交回复
热议问题