jus*_*oob 5 java spring spring-security thymeleaf
我正在使用Spring Boot和Thymeleaf开发应用程序.
我的自定义登录页面中有以下代码段:
<p th:if="${param.logout}">Logged out successfully</p>
Run Code Online (Sandbox Code Playgroud)
此段落与以下安全配置相关联:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "*.css").permitAll()
.antMatchers("/myendpoint").authenticated()
.and()
.formLogin().loginPage("/login").permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login?logout")
.permitAll();
}
Run Code Online (Sandbox Code Playgroud)
因此,在注销后,用户被重定向到/login?logout并显示注销消息.
我的问题是当用户/login?logout通过简单地写入http://myserver:8080/login?logout浏览器明确导航到时,也会显示此消息.
是否可以阻止用户直接访问/login?logout(因此仅在实际注销时显示消息)?
经过一番研究后,我想出了使用RedirectAttributes和addFlashAttribute()在注销时将数据传递到我的登录页面。
因此,我没有将其设置logout为查询参数,而是从安全配置中删除了 Spring 的默认注销处理:
http
.authorizeRequests()
.antMatchers("/", "*.css").permitAll()
.antMatchers("/myendpoint").authenticated()
.and()
.formLogin().loginPage("/login").permitAll();
Run Code Online (Sandbox Code Playgroud)
并在我的控制器中创建了以下自定义注销端点:
@PostMapping("/logout-user")
public String logout(HttpServletRequest request, RedirectAttributes attrs) {
new SecurityContextLogoutHandler().logout(request, null, null);
// this attribute will be received in /login
attrs.addFlashAttribute("logout", true);
return "redirect:/login";
}
Run Code Online (Sandbox Code Playgroud)
因此,我将注销请求发送到此端点并检查logout中的属性/login,以在适当的时候显示注销消息:
<p th:if="${logout}">Logged out successfully</p>
Run Code Online (Sandbox Code Playgroud)
它似乎工作完美。
| 归档时间: |
|
| 查看次数: |
128 次 |
| 最近记录: |