简体   繁体   English

Spring REST应用程序中安全性约束的Java配置

[英]Java configuration for security constraints in a Spring REST application

I am building an application with Spring REST (without web.xml ). 我正在使用Spring REST(没有web.xml )构建应用程序。 REST calls are working fine but I need to add few security constraints which are easy to add through web.xml but as I am using Spring 4 without web.xml so I need help in adding the web.xml part through Java configuration. REST调用工作正常,但我需要添加一些安全约束,这些约束很容易通过web.xml添加,但因为我使用没有web.xml的 Spring 4所以我需要帮助通过Java配置添加web.xml部分。

My web.xml : 我的web.xml

<security-role>
     <role-name>all</role-name>
</security-role>
<security-constraint>
    <web-resource-collection>
         <web-resource-name>test</web-resource-name>
         <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
         <role-name>all</role-name>
    </auth-constraint>
</security-constraint>


I need help in configuring this web.xml through Java configuration. 我需要帮助通过Java配置配置此web.xml Probably this can be added through Spring Security but not sure how to that. 可能这可以通过Spring Security添加,但不知道如何。

This is how you can implement security with your custom constraints using@Configuration and overrride the configure method of WebSecurityConfigurerAdapter class. 这是使用@Configuration通过自定义约束实现安全性并覆盖WebSecurityConfigurerAdapter类的configure方法的方法。

 @Configuration
    public class SecurityConfiguration extends WebSecurityConfigurerAdapter {


        @Autowired
        DataSource datasource;
        Logger logger = LoggerFactory.getLogger(getClass());

        @Override
        protected void configure(HttpSecurity http) throws Exception {

            http.httpBasic().and().authorizeRequests().antMatchers("/public/**")
                    .permitAll().antMatchers("/admin/**").hasAuthority("admin")
                    .antMatchers("/user/**").hasAuthority("user")
                    .and()
                    .logout()
                    // Logout requires form submit. Bypassing the same.
                    .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                    .logoutSuccessUrl("/index.html").and()
                    .addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class)
                    .csrf().disable();

        }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM