[SpringBoot Security] 1. 환경설정 & 2. 시큐리티 설정

Jimin·2023년 3월 7일
0
post-thumbnail
// WebMvcConfig.java

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        MustacheViewResolver resolver = new MustacheViewResolver();
        resolver.setCharset("UTF-8");
        resolver.setContentType("text/html; charset=UTF-8");
        resolver.setPrefix("classpath:/templates/");
        resolver.setSuffix(".html");

        registry.viewResolver(resolver);
    }
}
  • @Configuration 설정 파일
  • html 파일을 기본 타입으로 설정
    @GetMapping({"", "/"})
    public String index() {
        // 머스테치 기본폴더 src/main/resources
        // 뷰리졸버 설정 : templates(prefix), .mustache(suffix) -> yml 파일에 (그러나 생략가능 기본 설정됨)
        return "index"; // src/main/resources/templates/index.mustache
    }

  • 머스테치 기본 폴더: /src/main/resurces
  • 뷰리졸버 생성: templates(prefix), .mustance(suffix) 생략 가능
    • /src/main/resurces/templates/index.mustache

@GetMapping("/login")
이는 스프링 시큐리티가 해당 주소를 낚아챔

  • /localhost:8080/login

@Configuration
@EnableWebSecurity //활성화, 스프링 시큐리티 필터가 스프링 필터체인에 등록됨
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests()
                .antMatchers("/user/**").authenticated() // 인증만 되면 들어갈 수 있는 주소
                .antMatchers("/manager/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_MANAGER')")
                .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
                .anyRequest().permitAll()
                .and()
                .formLogin()
                .loginPage("/loginForm");
    }
}
  • 권한이 없는 사용자가 접근할 때 로그인 페이지로 이동함

0개의 댓글