Spring Security 실습 (blog)

[Spring] Security 실습
Feb 21, 2024
Spring Security 실습 (blog)
notion image

로그인 시스템 만들기

1. 기존 로그인 컨트롤러 주석 처리

notion image

2. Spring Boot Starter Security 라이브러리 다운

MVN Repository에서 다운
notion image
notion image
notion image
스프링 프레임 워크들은 버전을 안적어주는것이 좋다.
notion image
이렇게 수정(알아서 스프링의 버전을 잡아준다.)
notion image

3. 메인페이지 테스트 해보기

모든 페이지가 잠겨버림
notion image
notion image
username = user password = 2번의 해쉬코드

시큐리티 커스터마이징

1. config 패키지 생성

notion image

2. SecurityConfig 파일 생성

Web.xml과 비슷한 역할을 함. → SF가 SecurityConfig 파일을 보고 일을 한다.
notion image
@Configuration // 컴포넌트 스캔 public class SecurityConfig { @Bean SecurityFilterChain configure(HttpSecurity http) throws Exception { // 인증이 필요한 페이지 http.authorizeHttpRequests(a -> { a.requestMatchers("/user/updateForm", "/board/**").authenticated().anyRequest().permitAll(); }); http.formLogin(f -> { f.loginPage("/loginForm"); }); return http.build(); } }

3. 컨트롤러 인증 로직 삭제

notion image

4. 테스트 해보기

notion image
로그인 페이지로 이동

5. 예외 주소 설정

notion image
@Bean public WebSecurityCustomizer ignore(){ return w -> w.ignoring().requestMatchers("/board/*", "/static/**", "/h2-console/**"); }

시큐리티 로그인 구현하기

1. username 조회 메서드 만들기

public User findByUsername(String username) { Query query = em.createNativeQuery("select * from user_tb where username=?", User.class); query.setParameter(1, username); try { User user = (User) query.getSingleResult(); return user; }catch (Exception e){ return null; } }

2. MyLoginService 구현하기

notion image
notion image
notion image
notion image
boolean은 전부 return true로 해놓기
notion image
notion image
패스워드를 암호화해서 넣지않아서 오류가 남;
notion image

3. Mustache에서 사용가능한 세션 정보 저장

notion image
 
Share article

More articles

See more posts
RSSPowered by inblog