Search

15. 스프링부트 포토그램 인증 회원가입SecurityConfig 생성

포토그램 인증 구현하기

시큐리티 세팅

photogram 프로젝트 서버 켜주고
http://localhost:8080만 쳐서 들어가도
http://localhost:8080/login 으로 진입 주소로 들어가진다.
분명 8080 까지 쳐서 들어갔는데 변경되는 이유는 pom.xml에
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
XML
복사
시큐리티 관련 라이브러리가 등록되어 있다.
시큐리티 라이브러리가 뭐냐면
어떤 클라이언트가 내 홈페이지에 들어올라 할때 인증이 되지 않은 모든 사용자를 이 화면(로그인화면)으로 리다이렉션(어떤 주소 요청이 왔을 때 그 주소요청을 다른 주소로 변경)한다.
http://localhost:8080
http://localhost:8080/login 으로 리다이렉션 된 상태
f12 누르고 ctrl+r 누른채로 보면 login이 보인다
다시 주소창에서 8080까지만 치고 들어가면 localhost 부분도 보이게 되는데 코드가 302
302코드(요청한 리소스의 url가 일시적으로 변경)
주소 변경을 시큐리티가 해준거다.
근데 우리가 가고 싶은 페이지는 이 로그인 페이지가 아니라 인스타그램 로그인 페이지다.
셋팅 변경을 해주자.
config 폴더 생성
SecurityConfig.java 생성
package com.cos.photogramstart.config; public class SecurityConfig { }
Java
복사
시큐리티 설정 파일이 될려면 WebSecurityConfigurerAdapter로 상속받아야 한다.
package com.cos.photogramstart.config; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; public class SecurityConfig extends WebSecurityConfigurerAdapter { }
Java
복사
@Configuration 어노테이션을 줘서 IoC에 등록해줘야한다.
@Configuration //IoC public class SecurityConfig extends WebSecurityConfigurerAdapter {}
Java
복사
하지만 아직도 8080쳐도 기존의 시큐리티가 가로채는 화면으로 진입된다.
@EnableWebSecurity 어노테이션을 추가 해주면 해당 파일(SecurityConfig.java)로 시큐리티가 활성화 시킨다.
@EnableWebSecurity //해당 파일로 시큐리티를 활성화 @Configuration //IoC public class SecurityConfig extends WebSecurityConfigurerAdapter { }
Java
복사
저장하고 나면 console에 이렇게 오류가 나는데
========================== CONDITION EVALUATION DELTA ========================== Positive matches: ----------------- None Negative matches: ----------------- WebSecurityEnablerConfiguration: Did not match: - @ConditionalOnMissingBean (names: springSecurityFilterChain; SearchStrategy: all) found beans named springSecurityFilterChain (OnBeanCondition) Matched: - @ConditionalOnClass found required class 'org.springframework.security.config.annotation.web.configuration.EnableWebSecurity' (OnClassCondition) - found 'session' scope (OnWebApplicationCondition) Exclusions: ----------- None Unconditional classes: ---------------------- None
XML
복사
그냥 자바파일에 스페이스 하나 더 쳐주고 저장해주면 잘 돌아간다..ㅎㅎ
자동완성으로 보면 configure(HttpSecurity http) 라는게 있다.
눌러서 오버라이딩 해주자.
@EnableWebSecurity //해당 파일로 시큐리티를 활성화 @Configuration //IoC public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { // TODO Auto-generated method stub super.configure(http); } }
Java
복사
super.configure(http); 요거가 자꾸 주소를 가로채고 있어서 지워주고 저장
@Override protected void configure(HttpSecurity http) throws Exception { //super 삭제 - 기존 시큐리티가 가지고 있는 기능이 다 비활성화됨. }
Java
복사
이제 주소를 안낚아챈다.
이제 우리 주소로 낚아채게 해주자~~
인증이 되지 않은 모든 사용자는 인스타그램 로그인페이지로 이동시켜주자.
@Override protected void configure(HttpSecurity http) throws Exception { //super 삭제 - 기존 시큐리티가 가지고 있는 기능이 다 비활성화됨. http.authorizeRequests() .antMatchers("/", "/user/**", "/image/**", "/subscribe/**" , "/comment/**").authenticated() .anyRequest().permitAll(); }
Java
복사
여기서
http.authorizeRequests() // / , /user , /image, /subscribe, /comment로 시작하는 주소로 들어오면 인증필요 .antMatchers("/", "/user/**", "/image/**", "/subscribe/**" , "/comment/**").authenticated() // 그게 아닌 모든 요청은 허용 하겠다. .anyRequest().permitAll();
Java
복사
이런 뜻이다.
http://localhost:8080/
403 에러가 떨어진다.
403코드(접근할 권리를 가지고 있지 않다. 승인되지 않은 사용자.)
http://localhost:8080/image
image 주소로 접근해도 같은 형상이 들어온다.
위에 설정해준 주소가 아닌
http://localhost:8080/auth/signin
403 페이지가 뜨는 주소들(접근권한이 없는 페이지)을 로그인페이지로 이동하게 끔 하고싶다.
@Override protected void configure(HttpSecurity http) throws Exception { //super 삭제 - 기존 시큐리티가 가지고 있는 기능이 다 비활성화됨. http.authorizeRequests() .antMatchers("/", "/user/**", "/image/**", "/subscribe/**" , "/comment/**").authenticated() // / , /user , /image, /subscribe, /comment로 시작하는 주소로 들어오면 인증필요 .anyRequest().permitAll() // 그게 아닌 모든 요청은 허용 하겠다. .and() .formLogin() //form태그 및 input태그 중에 form태그로 로그인할 .loginPage("/auth/signin") //접근 권한이 없는 페이지(위에 설정한 주소)들은 다 이 주소로 이동. .defaultSuccessUrl("/"); //로그인을 정상처리하면 /로 이동 }
Java
복사
http://localhost:8080/ 접속해도 이제 로그인페이지로 이동한다.
302코드가 보인다.
시큐리티 셋팅이 완벽하게 된건 아니고 나중에 추가적으로 더 수정예정.

*참고