Spring Boot对每个请求进行身份验证

时间:2019-08-09 02:01:23

标签: java spring-boot authentication spring-security

我正在从事spring-boot并使用spring安全性进行身份验证。但是,登录存在问题。当我请求需要登录的URL时,它会将我重定向到登录页面,然后登录成功。但是,当用户登录时我请求相同的URL或另一个URL时,它将再次将我重定向到登录名。似乎身份验证无法识别用户已登录。以下是我的代码。 感谢您提供解决此问题的帮助。

@Configuration
@EnableWebSecurity
public class LoginSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/", "/find", "/forgotten", "/activation", "/reset-password", "/info/*",
                    "/css/**", "/js/**", "/img/**", "/login").permitAll()
            .antMatchers("/admin/*").access("hasRole('ADMIN')")
            .antMatchers("/user/**", "/project/**").access("hasRole('USER') or hasRole('ADMIN')")
            .and()
            .formLogin().successHandler(authenticationSuccessHandler())
            .loginPage("/login").failureUrl("/login?error")
            .and()
            .logout().logoutSuccessUrl("/").permitAll()
                .and()
                .exceptionHandling().accessDeniedPage("/403")
                .and()
                .csrf()
                .disable();
        }
}

这是loginController

@GetMapping("/login")
    public String showLogin(HttpServletRequest request, Model model, Principal principal, LoginForm loginForm) {
        String referer = request.getHeader("Referer");

        request.getSession().setAttribute(REDIRECT_URL_SESSION_ATTRIBUTE_NAME, referer);

        return principal == null ?  "login" : "redirect:/";
    }

    @PostMapping("/login-process")
    public String processLogin(@ModelAttribute("loginForm") final LoginForm loginForm,
                                final BindingResult bindingResult, Principal principal, HttpServletRequest request) {
        User user = userService.findValidUser(loginForm.getEmail());
        try {
            if (user != null && passwordEncoder.matches(hashWith256(loginForm.getPassword()), user.getPassword())) {
                if(user.getVerified() == UserVerified.VERIFIED.getValue()){
                    request.getSession().setAttribute("user", user);

                        Object redirectURLObject = request.getSession().getAttribute(REDIRECT_URL_SESSION_ATTRIBUTE_NAME);

                        if(redirectURLObject != null){
                            URI uri =  new URI(redirectURLObject.toString());

                            return "redirect:" + uri.getPath();
                        }

                }else {
                    bindingResult.rejectValue("email", "error", "Please verify your email via the email has been sent to you.");
                }
            }else {
                bindingResult.rejectValue("email", "error", "Invalid email or password.");
            }
        } catch (NoSuchAlgorithmException | URISyntaxException e) {
            LOG.error("An error occurred during login for user, " + user.getEmail(), e.getMessage());
        }

        if (bindingResult.hasErrors()) {
            return "login";
        }

        return "login";
    }

这是成功处理程序的实现

public class CustomAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler implements
    AuthenticationSuccessHandler {

public static final String REDIRECT_URL_SESSION_ATTRIBUTE_NAME = "REDIRECT_URL";

public CustomAuthenticationSuccessHandler() {
    super();
    setUseReferer(true);
}

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                    Authentication authentication) throws IOException, ServletException {
    Object redirectURLObject = request.getSession().getAttribute(REDIRECT_URL_SESSION_ATTRIBUTE_NAME);

    if(redirectURLObject != null)
        setDefaultTargetUrl(redirectURLObject.toString());
    else{
        setDefaultTargetUrl("/");
    }

    request.getSession().removeAttribute(REDIRECT_URL_SESSION_ATTRIBUTE_NAME);

    super.onAuthenticationSuccess(request, response, authentication);
}

}

1 个答案:

答案 0 :(得分:0)

您可以将不需要身份验证的路径与不需要身份验证的路径分开。请尝试如下重写:

def get_min_max(prices):
    min = 1000000
    max = -1000000
    for p in prices:
        if p > max:
            max = p
        if p < min:
            min = p
    return min, max