Spring 安全登录总是登陆一个没有消息的错误页面

ffu*_*tes 6 java spring spring-security

我在 Spring 中为一个小项目使用登录表单,但我有一个小问题,即每次我使用登录表单登录时,都会收到错误重定向。

这是我的 SecurityConfiguration.java

package com.ffuentese;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private DataSource dataSource;

    @Value("${spring.queries.users-query}")
    private String usersQuery;

    @Value("${spring.queries.roles-query}")
    private String rolesQuery;

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.
            jdbcAuthentication()
                .usersByUsernameQuery(usersQuery)
                .authoritiesByUsernameQuery(rolesQuery)
                .dataSource(dataSource)
                .passwordEncoder(bCryptPasswordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.
            authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/login").permitAll()
                .antMatchers("/registration").permitAll()
                .antMatchers("/**").hasAuthority("ADMIN").anyRequest()
                .authenticated().and().csrf().disable().formLogin()
                .loginPage("/login").failureUrl("/login?error=true")
                .defaultSuccessUrl("/home")
                .usernameParameter("email")
                .passwordParameter("password")
                .and().logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/").and().exceptionHandling()
                .accessDeniedPage("/access-denied");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web
           .ignoring()
           .antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**");
    }

}
Run Code Online (Sandbox Code Playgroud)

我的签到表:

<form th:action="@{/login}" method="POST" class="form-signin">
    <h3 class="form-signin-heading" th:text="Welcome"></h3>
    <br/>

    <input type="text" id="email" name="email"  th:placeholder="Email"
        class="form-control" /> <br/> 
    <input type="password"  th:placeholder="Password"
        id="password" name="password" class="form-control" /> <br /> 

    <div align="center" th:if="${param.error}">
        <p style="font-size: 20; color: #FF1C19;">Email or contraseña errónea, por favor intente nuevamente.</p>
    </div>
    <button class="btn btn-lg btn-primary btn-block" name="Submit" value="Login" type="Submit" th:text="Login"></button>
</form>
Run Code Online (Sandbox Code Playgroud)

我的 loginController.java

package com.ffuentese;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.ffuentese.User;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping(value={"/", "/login"}, method = RequestMethod.GET)
    public ModelAndView login(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("login");
        return modelAndView;
    }

    @RequestMapping(value="/home", method = RequestMethod.GET)
    public ModelAndView homeV(){
        ModelAndView modelAndView = new ModelAndView();
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        modelAndView.setViewName("home");
        return modelAndView;
    }


    @RequestMapping(value="/registration", method = RequestMethod.GET)
    public ModelAndView registration(){
        ModelAndView modelAndView = new ModelAndView();
        User user = new User();
        modelAndView.addObject("user", user);
        modelAndView.setViewName("registration");
        return modelAndView;
    }

    @RequestMapping(value = "/registration", method = RequestMethod.POST)
    public ModelAndView createNewUser(@Valid User user, BindingResult bindingResult) {
        ModelAndView modelAndView = new ModelAndView();
        User userExists = userService.findUserByEmail(user.getEmail());
        if (userExists != null) {
            bindingResult
                    .rejectValue("email", "error.user",
                            "There is already a user registered with the email provided");
        }
        if (bindingResult.hasErrors()) {
            modelAndView.setViewName("registration");
        } else {
            userService.saveUser(user);
            modelAndView.addObject("successMessage", "User has been registered successfully");
            modelAndView.addObject("user", new User());
            modelAndView.setViewName("registration");

        }
        return modelAndView;
    }

    @RequestMapping(value="/admin/home", method = RequestMethod.GET)
    public ModelAndView home(){
        ModelAndView modelAndView = new ModelAndView();
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        User user = userService.findUserByEmail(auth.getName());
        modelAndView.addObject("userName", "Welcome " + user.getName() + " " + user.getLastName() + " (" + user.getEmail() + ")");
        modelAndView.addObject("adminMessage","Content Available Only for Users with Admin Role");
        modelAndView.setViewName("admin/home");
        return modelAndView;
    }


}
Run Code Online (Sandbox Code Playgroud)

因此,不是从登录到 /home,它最终会登陆 /error。错误本身是这样一行代码:

{"timestamp":"2018-04-04T21:28:28.944+0000","status":999,"error":"None","message":"无可用消息"}

该表单确实有效,因为如果我从 /error 移动并转到任何受保护的 URL,它们可以被打开。

编辑:原始代码来自这个存储库,我将它改编成我自己的项目https://github.com/gustavoponce7/SpringSecurityLoginTutorial也在这里解释

编辑:我认为重要的另一点是,如果我登录然后再次登录,表单似乎可以正常工作,使用户按预期从登录到 /home。这很奇怪。

123*_*123 7

您可以将always-use-default-target参数添加到成功 URL。

.defaultSuccessUrl("/home",true)
Run Code Online (Sandbox Code Playgroud)

这意味着如果登录成功,您将始终被发送到/home.

我认为不良行为是由于某种原因导致错误页面排队,然后当登录成功时,您会“返回”该页面。

这不是理想的解决方案,但如果您不想在登录后转到上一页,那么它可以防止您描述的行为。


Jac*_*liś 2

也许就是这样,没有什么RequestMapping错误Param。可能的解决方案

@RequestMapping(value={"/", "/login"}, method = RequestMethod.GET)
    public ModelAndView login(@RequestParam(value = "error", required = false)){
        ModelAndView modelAndView = new ModelAndView();
        if (error != null) {
          modelAndView.setViewName("error page");
        } else modelAndView.setViewName("login");

        return modelAndView;
    }
Run Code Online (Sandbox Code Playgroud)

编辑1

也可能是由于您的项目中没有以下所有文件夹引起的"/static/**", "/js/**", "/css/**", "/img/**", "/json/**",请删除此配置或添加所有文件夹。