Enterprise Java

Spring Security

There are many authentication mechanisms (basic, digest, form, X.509, etc), and there are many storage options for credentials and authority information (in-memory, database, LDAP, etc). Authorization depends on authentication and determines if you have the required Authority. The decision process is often based on roles (e.g. ADMIN, MEMBER, GUEST, etc).

There are three steps to set up and configure Spring Security in a web environment:

  1. Setup the filter chain: The implementation is a chain of Spring configured filters (Spring Boot does it automatically)
  2. Configure security (authorization) rules
  3. Setup Web Authentication

In the next example, it is defined as specific authorization restrictions for URLs using mvcMatchers.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().loginPage("/login").permitAll().and().exceptionHandling().accessDeniedPage("/denied").and()
                .authorizeRequests().mvcMatchers("/accounts/resources/**").permitAll().mvcMatchers("/accounts/edit*")
                .hasRole("EDITOR").mvcMatchers("/accounts/account*").hasAnyRole("VIEWER", "EDITOR")
                .mvcMatchers("/accounts/**").authenticated().and().logout().permitAll().logoutSuccessUrl("/");
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new StandardPasswordEncoder()).withUser("viewerUser")
                .password("abc").roles("VIEWER").and().withUser("editorUser").password("abc").roles("EDITOR");
    }

}

As you can see, you can chain multiple restrictions (using the and() method). The first method sets up a form-based authentication. The second method uses a UserDetailsManagerConfigurer. You can use jdbcAuthentication() instead of inMemoryAuthentication().

Learn more at Spring Security Reference

Published on Java Code Geeks with permission by Eidher Julian, partner at our JCG program. See the original article here: Spring Security

Opinions expressed by Java Code Geeks contributors are their own.

Eidher Julian

Eidher Julian is a Systems Engineer and Software Engineering Specialist with 13+ years of experience as a Java developer. He is an Oracle Certified Associate and SOA Certified Architect.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button