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/**");
}
}
我的登录表格:
<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>
我的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;
}
}
因此,与其从登录名转到/ home,它最终登陆/ error。错误本身是一行这样的代码:
{“ timestamp”:“ 2018-04-04T21:28:28.944 + 0000”,“ status”:999,“ error”:“
None”,“ message”:“无可用消息”}
该表格确实有效,因为如果我从/ error移至任何受保护的URL,便可以将其打开。
编辑:原始代码来自此存储库,我将其调整为适合自己的项目https://github.com/gustavoponce7/SpringSecurityLoginTutorial也在此处进行了说明
EDit:我认为重要的一点是,如果我登录然后再次登录,则该表单似乎可以正常运行,从而使用户从登录名转到/ home即可。这很奇怪。
回答:
也许这就是这件事,也没有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;
}
编辑1
也可能是由于您的项目中没有以下所有文件夹"/static/**", "/js/**", "/css/**", "/img/**",
"/json/**",删除此配置或添加所有文件夹。
以上是 Spring Security登录始终落在没有消息的错误页面中 的全部内容, 来源链接: utcz.com/qa/403536.html