With Spring, the recommended protection method is to set Spring Security to take care of authentication strong> and authorization .
Authentication
For authentication strong> , there are ready methods (JDBC, LDAP) or you can create your own implementation .
JDBC-based authorization example:
@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
For authorization , you can protect by URL or method. In fact, there are other possibilities (like using the Aspect Guidance paradigm), but the two presented here are the fundamental ones.
URL Protection
Via code, you can 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, the <intercept-url>
tag exists. 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>
Method protection via annotation
You can enable annotation authorizations in Spring beans with the following setting:
<global-method-security pre-post-annotations="enabled"/>
The most useful and commonly used security annotation is @PreAuthorize
, which checks to see 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 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.