페이지 권한 설정 > 스프링 부트

본문 바로가기

[개발] 페이지 권한 설정

필기자
2022-11-01 14:27 2,284 0

본문

templates/item/itemForm.html



<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{layouts/layout1}">

<div layout:fragment="content">
  <h1>상품등록 페이지입니다.</h1>
</div>
</html>

 

kr/hull/shop/controller/ItemController.java



@Controller
public class ItemController {
    @GetMapping(value = "/admin/item/new")
    public String itemForm(Model model){
        return "item/itemForm";
    }
}

 

kr/hull/shop/config/CustomAuthenticationEntryPoint.java



public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");

        //LOGGER.info("가입되지 않은 사용자 접근");
        //response.sendRedirect("/signin");
    }
}

 

kr/hull/shop/config/SecurityConfig.java 추가



@Configuration
@EnableWebSecurity
public class SecurityConfig {
    // Spring Security 5.7.0-M2 부터 기존 WebSecurityConfigureAdapter 방식에서 SecurityFilterChain 으로 변경 권장
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        // 인증이 필요한 요청폼 설정
        http.formLogin()
                .loginPage("/members/login")
                .defaultSuccessUrl("/")
                .usernameParameter("email")
                .failureUrl("/members/login/error")
                .and()
                .logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/members/logout"))
                .logoutSuccessUrl("/")
        ;

        http.authorizeRequests()
                .mvcMatchers("/css/**", "/js/**", "/img/**").permitAll()
                .mvcMatchers("/", "/members/**", "/item/**", "/images/**").permitAll()
                .mvcMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
        ;

        //인증 실패시 라우팅 or 인증 회원이 아닌 사용자가 제한 리소스 접근시
        http.exceptionHandling()
                .authenticationEntryPoint(new CustomAuthenticationEntryPoint())
        ;

        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

 

결과 : http://localhost:8080/admin/item/new

 

20221101142303_58c21c62e2e6f71b42558e4bc6ecc1e2_v6am.png

 

20221101142629_58c21c62e2e6f71b42558e4bc6ecc1e2_aa7n.png

 

20221101142539_58c21c62e2e6f71b42558e4bc6ecc1e2_1eu2.png

 

20221101142745_58c21c62e2e6f71b42558e4bc6ecc1e2_ztej.png

댓글목록0

등록된 댓글이 없습니다.
게시판 전체검색