Spring Security Basics - JamesDansie/data-structures-and-algorithms GitHub Wiki

Spring Security Basics

Author: James Dansie

Steps to setup a spring authentication app;

  1. Add stuff to add for spring from start.spring.io; devtools, web, spring security, thymeleaf, jpa, postgres.
  2. application.properties - add the postgres url
spring.datasource.url=jdbc:postgresql://localhost:5432/albums
#comment out after making the database. It will rewrite every time
spring.jpa.hibernate.ddl-auto=update
#spring.datasource.url=jdbc:${DATABASE_URL}
  1. By default you will be directed to the log in page.
  2. Make a config package with a WebSecurityConfig class. Copy pasta from https://spring.io/guides/gs/securing-web/ under src/main/java/hello/WebSecurityConfig.java.
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

    @Bean
    @Override
    public UserDetailsService userDetailsService() {
        UserDetails user =
             User.withDefaultPasswordEncoder()
                .username("user")
                .password("password")
                .roles("USER")
                .build();

        return new InMemoryUserDetailsManager(user);
    }
}

.antMatchers("/", "/home").permitAll() lets people hit the home page, even if they're not logged in. Also you want to allow everyone (even not logged in users) to go to the log in page.

  1. Add a ApplicationUser class (NOT a User class) with id (generated user), username, password. Implements UserDetails, then implement the methods of UserDetails interface.
  2. Make a JpaRepo for the ApplicationUser;
public interface ApplicationUserRepository extends JpaRepository <ApplicationUser, Long> {
    public ApplicationUser findByUsername(String username);
}
  1. Make a post request for making users - make new users, save them to the repo (auto wire it up). Add a passwordEncoder to pass your passwords through (autowire it up).
  2. Make UserDetailsServiceImpl that implements UserDetailsService - to solve the error implement the methods. Have ApplicationUser implement UserDetails.
  3. Set UserDetails booleans to true. Use intelliJ to implement the methods.
  4. WebSecurityConfig needs UserDetailService autowired.
  5. Make initial psql database, but leave it blank. Set #spring.jpa.hibernate.ddl-auto=update to create initially, then change to update.
  6. ...more witchcraft, check the cheat sheet and lab instructions.

References