How to handle security in a REST application with Spring?

Asked

Viewed 1,659 times

5

I would like to know how I could treat the security of a stateless REST application with Spring.

Imagine that no user can access any content from /app/content if you have not identified first. There is how to do this without also need to do treatment in all methods?

1 answer

8


With Spring, the recommended protection method is to configure the Spring Security to take care of the authentication and authorization.

Authentication

To the authentication, there are ready methods (JDBC, LDAP) or you can create your own implementation.

Example of JDBC-based authorization:

@Autowired
private DataSource dataSource;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth
        .jdbcAuthentication()
            .dataSource(dataSource)
            .withDefaultSchema()
            .withUser("user").password("password").roles("USER").and()
            .withUser("admin").password("password").roles("USER", "ADMIN");
}

Authorization

To the authorization, you can protect by URL or method. In fact, there are other possibilities (such as using the Aspect Orientation paradigm), but the two presented here are the fundamental ones.

URL protection

Via code, it is possible to configure paper access to different Urls using an instance of HttpSecurity. Example:

protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .and()
        .httpBasic();
}

More complex example:

protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()                                                                
            .antMatchers("/resources/**", "/signup", "/about").permitAll()                  
            .antMatchers("/admin/**").hasRole("ADMIN")                                      
            .antMatchers("/db/**").access("hasRole('ROLE_ADMIN') and hasRole('ROLE_DBA')")  
            .anyRequest().authenticated()                                                   
            .and()
        // ...
        .formLogin();
}

Via XML, there is a tag <intercept-url>. Example:

<http use-expressions="true">
    <intercept-url pattern="/**" access="authenticated"/>
    <intercept-url pattern="/admin*"
        access="hasRole('admin') and hasIpAddress('192.168.1.0/24')"/>
    <form-login />
    <http-basic />
</http>

Protection by method via annotation

It is possible to activate authorizations via annotation in Beans spring with the following configuration:

<global-method-security pre-post-annotations="enabled"/>

The most useful and commonly used security annotation is the @PreAuthorize, which checks if the user really could be running that method.

Example:

@PreAuthorize("hasRole('ROLE_USER')")
public void create(Contact contact);

Here the annotation was included in a interface, but could also be in the concrete class. This depends somewhat on the architecture used in your application.

Considerations

The topics mentioned are just a very brief summary of Spring Security. There are several other extension and customization points that can be used depending on the context.

I just hope this was a useful introduction.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.