gpt4 book ai didi

java - 我的 Spring SecurityConfig 没有被获取

转载 作者:行者123 更新时间:2023-12-01 12:37:51 24 4
gpt4 key购买 nike

我创建了一个基于 this tutorial 的小型网络应用程序。原始版本按预期工作。然后我做了一些更改,它停止工作,也就是说我可以在不登录的情况下访问/hello 页面。我正在学习这个神奇的自动配置世界,我想了解我的代码和原始代码之间的关键区别在哪里。

所以我有初始化程序,因为我不需要 main 东西,我只想要一个网络应用程序:

public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer  {

@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}

@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebConfig.class, SecurityConfig.class };
}

@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}

}

然后我有这个:

//@EnableWebMvc
// I tried with and without this annotation, no difference
// I guess as I extend WebMvcConfigurerAdapter I don't need this
@ComponentScan
@Configuration
@EnableAutoConfiguration
public class WebConfig {

}

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/home").setViewName("home");
registry.addViewController("/").setViewName("home");
registry.addViewController("/hello").setViewName("hello");
registry.addViewController("/login").setViewName("login");
}

}

最后是安全部分:

@配置@EnableWebMvcSecurity

public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/", "/home").permitAll()
.anyRequest().authenticated();
http.formLogin().loginPage("/login").permitAll().and().logout()
.permitAll();
}

@Configuration
protected static class AuthenticationConfiguration extends
GlobalAuthenticationConfigurerAdapter {

@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}

}
}

这些类都在同一个包中。如果有人向我解释这不起作用的原因是什么,我会很高兴。

最佳答案

SecurityConfig.class 需要位于根应用程序上下文中,而不是位于 servlet 应用程序上下文中;因此写出以下内容

@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { SecurityConfig.class };
}

@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebConfig.class };
}

在您的Initializer类中。

您可能想查看这篇博文:https://spring.io/blog/2013/07/03/spring-security-java-config-preview-web-security .

关于java - 我的 Spring SecurityConfig 没有被获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25411616/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com