我在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;
}
也可能是由于您的项目中没有以下所有文件夹"/static/**", "/js/**", "/css/**", "/img/**", "/json/**"
,删除此配置或添加所有文件夹。
我正在尝试为wordpress开发一个登录ajax表单。这个插件似乎工作得很好。如果我插入了正确的用户名和密码,登录将正常工作并显示正确的消息,然后重定向到正确的页面,但是如果我插入了错误的用户名和密码值,则不会发生任何情况,错误消息也不会出现。 似乎该函数是_wp_error,不回显该错误。 你知道为什么吗?低于我的代码 感谢在adv. PHP 超文本标记语言 JS
问题内容: 我正在使用Spring Security。我想显示登录错误消息,例如登录失败或帐户被锁定。如何在登录页面上显示此类消息? 问题答案: 只需配置为,然后从该servlet设置属性即可,例如 并将此请求转发到登录页面。 或提供 如 检查jsp上的参数 并有条件地打印消息
我使用JAAS成功地保护了我的web应用程序,为此我遵循了该页面上的教程http://www . the javageek . com/2013/09/18/configure-JAAS-JBoss-7-1-MySQL/ 我想在登录页面上向用户显示一条简洁的错误消息,而不是让他单击某个链接或按回键再次导航到登录页面。这可以做到吗?
我希望我的这个登录页面加载两次,即第一次用户输入username和password,然后从servlet获得响应,然后它将被重定向到带有“messages”的登录jsp页面。 我有两个按钮用于登录和注销。这个脚本可以像我试过的那样通过使用count变量加载两次吗?任何其他方法也将是首选。 附注:我试过使用和但它们不起作用。 login.jsp:-