如何在自定义登录页面中使用Spring Security检查附加参数?

时间:2018-12-25 07:56:31

标签: java spring spring-security

我是Java Spring Framework的新手。我想在用户登录时检查参数。我可以写customAuthenticationProvider,查看参数并检查它。问题是参数错误时我无法停止默认登录。

我该怎么办?

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired(required = false)
    private HttpServletRequest request;

    @Autowired(required = false)
    private HttpSession session;

    private static final String CAPTCHA2 = "CAPTCHA";

    public CustomAuthenticationProvider() {
        // nothing
    }

    @Override
    public Authentication authenticate(Authentication authentication)
            throws AuthenticationException {
        System.out.println("--- In Login method ----");

        String requestCaptcha = request.getParameter("captcha");
        String sessionCaptcha = session.getAttribute(CAPTCHA2).toString();
        System.out.println("request captcha= " + requestCaptcha);
        System.out.println("session captcha= " + sessionCaptcha);

        String name = authentication.getName();
        String password = authentication.getCredentials().toString();

        if(requestCaptcha.equals(sessionCaptcha)){
            return null;
        }
        else {
            System.out.println("problem");
            throw new BadCredentialsException("Wrong Captcha.");
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }
}

0 个答案:

没有答案