Spring Security Java配置。规则不适用

时间:2016-02-10 08:59:54

标签: java spring rest spring-security

我开始使用Spring Security。我一直都在实施自己的安全措施。所以这对我来说是新的。我已经完成了一些教程。我甚至读过Pro Spring Security Book(不幸的是,每个思想都配置了xml)。

我想在Spring和Spring Security上编写Rest Api。我将有主要路线到我的api。首先是匿名用户,具体如下: http://localhost:8080/cms/services/anonymous/**

第二个网址是针对经过身份验证的用户: http://localhost:8080/cms/services/authenticated/**

当我按下这样的url时: http://localhost:8080/cms/services/authenticated/testService/getInfo 我应该得到http答案401 Unauthorized。但在我目前的项目中,我得到200 Ok。我做错了什么?

这是我的配置:

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>

请帮忙。

1 个答案:

答案 0 :(得分:1)

您应该在SecurityConfig中注册AbstractAnnotationConfigDispatcherServletInitializer,如下所示:

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[] { "/" };
    }
}