메뉴 사용권한 설정 (로그인 후 사용가능)

han.user();·2023년 8월 1일
0

회원기능과 로그인기능을 구현했는데 사실상 그것들이 아무데도 사용되고 있지 않아,

챗봇메뉴는 로그인을 해야지만 사용가능하도록 설정해보고자 한다.

  1. 우선, SecurityConfig클래스 파일을 만들었다.
    SecurityConfig 클래스는 스프링 시큐리티를 사용하여 애플리케이션의 보안 설정을 구성한다.
package hankyungsoo.project.security;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/wordList/chatbot").authenticated() // 챗봇 페이지는 인증된 사용자만 접근 가능
                .anyRequest().permitAll() // 다른 요청은 모두 허용
            .and()
            .formLogin() // 로그인 페이지 사용
                .loginPage("/member/login") // 커스텀 로그인 페이지 경로 설정 (로그인 페이지 URL에 맞게 수정)
                .defaultSuccessUrl("/wordList/chatbot") // 로그인 성공 시 이동할 페이지
            .and()
            .logout()
                .logoutSuccessUrl("/wordList"); // 로그아웃 시 이동할 페이지
    }
}
  1. pom.xml에 의존성을 추가해준다.
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
  1. ChatbotController에 있던 기존 /chatbot 이동 메소드를 수정해준다.
//	@GetMapping("/chatbot")
//	public String chatbotPage() {
//		return "chatbot";
//	}

	@GetMapping("/chatbot")
    public String chatbotPage(HttpSession session) {
        // 세션에서 "authenticated" 속성을 가져와서 로그인 상태를 체크
        Boolean isAuthenticated = (Boolean) session.getAttribute("authenticated");
        if (isAuthenticated != null && isAuthenticated) {
            return "chatbot"; // 로그인 상태인 경우 챗봇 페이지로 이동
        } else {
            return "redirect:/member/login"; // 로그인하지 않은 경우 로그인 페이지로 리다이렉트
        }
    }

이렇게 수정하면 로그인이 되지 않은 상태에서 챗봇버튼을 누르면 로그인창이 나오고 로그인 후에는 정상적으로 이용이 가능하다.

profile
I'm still hungry.

0개의 댓글