[英]Spring boot authenticate for every request
我正在使用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);
}
}
您可以将不需要身份验证的路径与需要身份验证的路径分开。 请尝试如下重写:
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/find")
.antMatchers("/forgotten")
.antMatchers("/activation")
.antMatchers("/reset-password")
.antMatchers("/info/**")
.antMatchers("/css/**")
.antMatchers("/js/**")
.antMatchers("/img/**")
.antMatchers("/login");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.addFilterBefore(authenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("USER", "ADMIN")
.antMatchers("/project/**").hasAnyRole("USER", "ADMIN")
.and()
.formLogin()
.loginPage("/login")
.usernameParameter("login")
.passwordParameter("password")
.failureUrl("/login?error=true")
.permitAll()
.and()
.and()
.logout().logoutSuccessUrl("/").permitAll()
.and()
.exceptionHandling().accessDeniedPage("/403")
.and()
.csrf().disable();
}
protected UsernamePasswordAuthenticationFilter authenticationFilter() throws Exception {
UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
filter.setAuthenticationManager(authenticationManagerBean());
filter.setAuthenticationSuccessHandler(authenticationSuccessHandler());
return filter;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.