Reputation: 605
I have added these dependencies:
groupID: org.springframework.security
ArtifactId: spring-security-config, spring-security-taglibs, spring-security-web for Spring Security.
I have created simple controller with one request:
@Controller
public class ServerController {
@RequestMapping(value = "/get", method = RequestMethod.GET)
public @ResponseBody Object hello() {
return "helloWorld";
}
}
My configuration with use annotation:
@Configuration
@EnableWebMvc
@ComponentScan("web")
public class Dispatcher extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/WEB-INF/pages/**").addResourceLocations("/pages/");
}
@Bean
public InternalResourceViewResolver setupViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}
And Initializer for Spring application:
public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] {
Dispatcher.class,
};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] {
Dispatcher.class
};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
After, I have created ConfigSecurity, here he is:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/get/**").access("hasRole('USER')")
.and().formLogin().permitAll()
.and().logout.permitAll();
}
@Override
public void configure(AuthenticationManagerBuilder authentication) throws Exception {
authentication.inMemoryAuthentication().withUser("user").password("qwerty").roles("USER");
}
}
I don't know that I miss, but this doesn't work, I can visit /hello page without problem. Help me, please. Thanks!
Upvotes: 1
Views: 566
Reputation: 2975
You need to register your SecurityConfig class in your Initializer class.
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { SecurityConfig.class };
}
Upvotes: 2