1

I am starting to use Spring Security. I've always implement my own security. So this is new for me. I've followed few tutorials. I've read even Pro Spring Security Book (unfortunatelly everythink was configured with xml).

I would like to write Rest Api base on Spring and Spring Security. I will have to main routes to my api. First is for anonymous users, and this goes as follow: http://localhost:8080/cms/services/anonymous/**

The second url route is for authenticated users: http://localhost:8080/cms/services/authenticated/**

When I hit url like this: http://localhost:8080/cms/services/authenticated/testService/getInfo I should get http answer 401 Unauthorized. But in my current project I am getting 200 Ok. What I am doing wrong?

Here is my config:

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
    return new Class[] { AppConfig.class };
    }

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

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

@EnableWebMvc
@Configuration
@ComponentScan("pl.korbeldaniel.cms.server")
@Import({ SecurityConfig.class })
public class AppConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
    }

    @Bean(name = "messageSource")
    public ReloadableResourceBundleMessageSource getMessageSource() {
    ReloadableResourceBundleMessageSource resource = new ReloadableResourceBundleMessageSource();
    resource.setBasename("classpath:messages");
    resource.setDefaultEncoding("UTF-8");
    return resource;
    }

    @Override
    public void configureMessageConverters(final List<HttpMessageConverter<?>> converters) {
    super.configureMessageConverters(converters);
    converters.add(new MappingJackson2HttpMessageConverter());
    }
}

@Configuration
@ComponentScan("pl.korbeldaniel.cms.server")
@EnableWebSecurity
// @EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableGlobalMethodSecurity(securedEnabled = true)
@PropertySource("classpath:jdbc.properties")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    Environment env;

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().withUser("temporary").password("temporary").roles("ADMIN").and().withUser("user").password("userPass").roles("USER");
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
    http.httpBasic().and().authorizeRequests().//
        antMatchers("/cms/services/authenticated/**").authenticated().//
        antMatchers("/cms/services/anonymous/**").anonymous().and().//
        csrf().disable();
    }

    @Bean
    public DataSource getDataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
    dataSource.setUrl(env.getProperty("jdbc.url"));
    dataSource.setUsername(env.getProperty("jdbc.username"));
    dataSource.setPassword(env.getProperty("jdbc.password"));
    return dataSource;
    }
}

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">
    <!-- Name the application -->
    <display-name>Rest GWT</display-name>
    <description>This is web-project for cms</description>
    <servlet>
        <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/classes/action-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
        <url-pattern>/services/*</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>cms.html</welcome-file>
    </welcome-file-list>
</web-app>

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <!-- Scans the classpath of this application for @Components to deploy as 
        beans -->
    <context:component-scan base-package="pl.korbeldaniel.cms" />
    <!-- Configures the @Controller programming model -->
    <mvc:annotation-driven />
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <!-- <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" /> -->
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
            </list>
        </property>
    </bean>
</beans>

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- registers all of Spring's standard post-processors for annotation-based configuration -->
<context:annotation-config />
</beans>

Please help.

masterdany88
  • 5,041
  • 11
  • 58
  • 132

1 Answers1

1

You should register your SecurityConfig in AbstractAnnotationConfigDispatcherServletInitializer, like following:

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

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

    @Override
    protected String[] getServletMappings() {
    return new String[] { "/" };
    }
}
Ali Dehghani
  • 46,221
  • 15
  • 164
  • 151
  • I've followed Your instruction, and still the same: `200 OK` answer. By `SecurityConfig.class` You mean my configuration class? I've imported: `pl.korbeldaniel.cms.server.config.security.SecurityConfig;` – masterdany88 Feb 10 '16 at 09:19
  • Remove your xml configs – Ali Dehghani Feb 10 '16 at 09:23
  • All? Or concret one? – masterdany88 Feb 10 '16 at 09:23
  • I can not get rid of web.xml file cause my project does not compie: `[ERROR] Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.2:war (default-war) on project cms: Error assembling WAR: webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode) -> [Help 1] ` – masterdany88 Feb 10 '16 at 09:34
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/103062/discussion-between-masterdany88-and-ali-dehghani). – masterdany88 Feb 10 '16 at 09:36
  • Hey. Can You look at this post: https://stackoverflow.com/questions/35349799/restygwt-custom-dispatcher-dosent-work. Maybe You could help me once more? – masterdany88 Feb 12 '16 at 11:15