Spring Security Basics - JamesDansie/data-structures-and-algorithms GitHub Wiki
Spring Security Basics
Author: James Dansie
Steps to setup a spring authentication app;
- Add stuff to add for spring from start.spring.io; devtools, web, spring security, thymeleaf, jpa, postgres.
- 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}
- By default you will be directed to the log in page.
- 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.
- Add a ApplicationUser class (NOT a User class) with id (generated user), username, password. Implements UserDetails, then implement the methods of UserDetails interface.
- Make a JpaRepo for the ApplicationUser;
public interface ApplicationUserRepository extends JpaRepository <ApplicationUser, Long> {
public ApplicationUser findByUsername(String username);
}
- 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).
- Make UserDetailsServiceImpl that implements UserDetailsService - to solve the error implement the methods. Have ApplicationUser implement UserDetails.
- Set UserDetails booleans to true. Use intelliJ to implement the methods.
- WebSecurityConfig needs UserDetailService autowired.
- Make initial psql database, but leave it blank. Set #spring.jpa.hibernate.ddl-auto=update to create initially, then change to update.
- ...more witchcraft, check the cheat sheet and lab instructions.