我正在构建Spring Security应用程序。登录和注销工作正常,但是我想使未登录的用户无法注销,默认情况下是可能的(奇怪...)。
我试图为/ logout添加一个自定义控制器(检查用户是否已通过身份验证),但似乎没有任何效果。有没有办法在弹簧配置中做到这一点?下面是我的代码。控制器不工作。即使用户未通过身份验证,默认的spring-security / logout视图也是可见的。
function logout(router: Router, userSrv: userService) {
router.navigateByUrl('auth');
userSrv.user.next(undefined);
}
答案 0 :(得分:0)
您需要通过WebSecurityConfig
方法中的configure
类处理注销URL的权限,您已经对某些URL进行了处理,因此请更改为类似以下内容:
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**").permitAll() // This will be your home screen URL
.antMatchers("/css/**").permitAll()
.antMatchers("/assets/css/js/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/logoutSuccessful")
.permitAll()
.deleteCookies("JSESSIONID")
.invalidateHttpSession(true)
.and()
.exceptionHandling()
.accessDeniedHandler(new CustomAccessDeniedHandler())
;
}
注意添加
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/logoutSuccessful")
.permitAll()
.deleteCookies("JSESSIONID")
.invalidateHttpSession(true)
这是我们的注销处理代码,因此,如果用户点击/logout
,他们将被注销并转发到/logoutSuccessful
(我通常会在这里重定向到login
页面)。
您还可以在此处添加一系列其他方法来配置注销。注销与登录一样可配置,因此您可以根据需要添加注销处理程序。
答案 1 :(得分:0)
最后找到了解决方案。看来,用户转到/ logout后显示的“您确定...”页面是CSRF模块生成的。打开CSRF后,该页面不再显示。但是,这不是解决方案,因为需要启用csrf以获得安全性。缺少一行: .logoutRequestMatcher(新的AntPathRequestMatcher(“ / logout”)) 。现在,用户无需登录即可进入/ logout后注销。这不是我想要的解决方案,但现在可以解决问题;)。谢谢大家的答复。
package com.example.demo.config;
import com.example.demo.security.CustomAccessDeniedHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public AccessDeniedHandler accessDeniedHandler() {
return new CustomAccessDeniedHandler();
}
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**").permitAll() // This will be your home screen URL
.antMatchers("/css/**").permitAll()
.antMatchers("/assets/css/js/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().permitAll()
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login")
.deleteCookies("JSESSIONID")
.invalidateHttpSession(true)
.and()
.exceptionHandling()
.accessDeniedHandler(new CustomAccessDeniedHandler())
;
}
}