我正在尝试使用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未找到例外。
我花了一整天时间努力让它发挥作用。有人有想法如何解决这个问题吗?
PS如果我将logoutUrl设置为“/ logout”,我应该制作一个控制器来处理这个URL吗?
答案 0 :(得分:1)
你的logOut mechanizm不起作用......这是否意味着你的logIn mechanizm工作正常? 在这种情况下,真的,尝试处理你的&#39; / logOut&#39;网址:
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&#39;方法:
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之后添加。在&#39;配置&#39;方法这个(如果你不使用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;
}