Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Security Java configuration

I have working XML-based security configuration in my Spring MVC project:

<security:http use-expressions="true"
               authentication-manager-ref="authenticationManager">
    <security:intercept-url pattern="/" access="permitAll"/>
    <security:intercept-url pattern="/dashboard/home/**" access="hasAnyRole('ROLE_USER, ROLE_ADMIN')"/>
    <security:intercept-url pattern="/dashboard/users/**" access="hasRole('ROLE_ADMIN')"/>
    <security:intercept-url pattern="/rest/users/**" access="hasRole('ROLE_ADMIN')"/>
    <security:form-login login-page="/"/>
</security:http>

And I have question: is it possible to fully replace it by Java configuration? What annotations and where should I use for "use-expressions", "intercept-url", etc.?

like image 323
Dmytro Titov Avatar asked Mar 23 '14 12:03

Dmytro Titov


People also ask

What is Spring Security Config?

This article is an introduction to Java configuration for Spring Security which enables users to easily configure Spring Security without the use of XML. Java configuration was added to the Spring framework in Spring 3.1 and extended to Spring Security in Spring 3.2 and is defined in a class annotated @Configuration.

What is anyRequest () authenticated ()?

anyRequest(). authenticated() is that any request must be authenticated otherwise my Spring app will return a 401 response.


1 Answers

Yes, if you are using Spring security 3.2 and above, it will be something like this :

@Configuration
@EnableWebSecurity
public class MyWebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/dashboard/home/**").hasAnyRole("USER", "ADMIN")
                .antMatchers("/dashboard/users/**").hasRole("ADMIN")
                .antMatchers("/rest/users/**").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/")
                .permitAll();
    }

    // Possibly more overridden methods ...
}
like image 82
Jean-Philippe Bond Avatar answered Oct 03 '22 01:10

Jean-Philippe Bond