Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java configuration for security constraints in a Spring REST application

I am building an application with Spring REST (without 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.

My 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. Probably this can be added through Spring Security but not sure how to that.

like image 361
JDev Avatar asked Apr 16 '26 10:04

JDev


1 Answers

This is how you can implement security with your custom constraints using@Configuration and overrride the configure method of WebSecurityConfigurerAdapter class.

 @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();

        }
}
like image 136
Deepanjan Avatar answered Apr 18 '26 22:04

Deepanjan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!