我正在尝试使用Java配置设置Spring Security + mvc,但由于某种原因它不起作用,我得到404错误。
在我实现的WebApplicationInitializer类中,我以下一种方式注册安全过滤器
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
...
FilterRegistration.Dynamic securityFilterChain = servletContext.addFilter("springSecurityFilterChain", DelegatingFilterProxy.class);
securityFilterChain.addMappingForUrlPatterns(null, false, "/*");
..
SecurityContext列表
@Configuration
@EnableWebSecurity
public class SecurityContext extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsService userDetailsService;
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
// BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
// auth.userDetailsService(userDetailsService).passwordEncoder(encoder);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/assets/**").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/profile/**").hasAnyRole("ADMIN", "USER")
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/profile")
.failureUrl("/login?error")
.usernameParameter("username")
.passwordParameter("password")
.permitAll()
// .and()
// .logout()
// .logoutUrl("/logout")
// .logoutSuccessUrl("/")
// .permitAll()
.and()
.exceptionHandling().accessDeniedPage("/403");
}
}
对于logoutUrl,我尝试了所有的组合,没有运气…当我试图使用这个链接在我的jsp页面
<c:url value='/j_spring_security_check' />
我得到404 not found exception.
我花了一整天的时间试图让它工作。有人有解决这个问题的办法吗?
PS如果我将logoutUrl设置为"/logout",我应该做一个控制器来处理这个url吗?
您的注销机制不起作用…这是否意味着您的登录机制工作正常?在这种情况下,真的,尝试处理您的'/logOut' url:
public LogInController{
...
@RequestMapping(value = "/logOut", method = RequestMethod.GET)
public String logOut(ModelMap model) {
//Redirect to your start page (mapping the url '/welcome' for example)
return "redirect:welcome";
}
...
}
如果没有,检查你是否已经添加了你的安全配置文件到你的'onStartup'方法:
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext rootContext =
new AnnotationConfigWebApplicationContext();
//adding your main config class
rootContext.register(WebAppConfig.class);
//adding your security config class
rootContext.register(SecurityConfiguration.class);
...
}
那么你可以尝试添加后http。在'configure'方法中(如果在授权之前不使用CSRF令牌):
csrf().disable()
检查其他豆子:
@Bean
public ProviderManager providerManager() {
List<AuthenticationProvider> list = new ArrayList<AuthenticationProvider>();
list.add(daoAuthenticationProvider());
return new ProviderManager(list);
}
//If you use this filter (I think so, because you've defined 'username' and 'password' in
'configure' method)
@Bean
public UsernamePasswordAuthenticationFilter filter() {
UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
filter.setAuthenticationManager(providerManager());
return filter;
}