我使用Spring Security Basic Authentication和thymeleaf处理登录和注销表单。
我的问题是我的退出链接显示为按钮。但我希望将其包含在<a href="">
标记中。但是当我在<a href="">
标记中包含我的注销链接时,它不起作用。这是我的代码。
注销控制器 - Spring Boot
@RequestMapping(value = {"/logout"}, method = RequestMethod.POST)
public String logoutDo(HttpServletRequest request,HttpServletResponse response){
HttpSession session= request.getSession(false);
SecurityContextHolder.clearContext();
session= request.getSession(false);
if(session != null) {
session.invalidate();
}
for(Cookie cookie : request.getCookies()) {
cookie.setMaxAge(0);
}
return "redirect:/login?logout";
}
退出表单 - 前端
<form th:action="@{/logout}" method="POST">
<input type="submit" value="Logout"/>
</form>
安全配置
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.requestMatchers()
.antMatchers("/login", "/", "/customer/**", "/registration", "/admin/**")
.and()
.authorizeRequests()
.antMatchers("/admin/**").hasAuthority("ADMIN").antMatchers("/customer/**").hasAuthority("CUSTOMER")
.antMatchers("/login", "/registration", "/").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic().and().csrf().disable()
.formLogin() //login configuration
.loginPage("/login")
.loginProcessingUrl("/login")
.usernameParameter("email")
.passwordParameter("password")
.defaultSuccessUrl("/customer/home")
.and().logout() //logout configuration
.logoutUrl("/logout")
.logoutSuccessUrl("/login")
.and().exceptionHandling() //exception handling configuration
.accessDeniedPage("/error");
}
答案 0 :(得分:3)
解决方法是提交“隐藏”表单:
<a href="javascript: document.logoutForm.submit()" > Logout Link </a>
<form name="logoutForm" th:action="@{/logout}" method="post" th:hidden="true">
<input hidden type="submit" value="Logout"/>
</form>