inflearn logo
강의

Course

Instructor

Spring Boot Security & JWT Lecture

Spring Boot Security 5 - Authorization

[5강] admin, manager로 로그인시 403에러

919

sue0007316831

1 asked

0

안녕하세요! 강의 잘 듣고 있습니다.

다름이 아니라 5강을 진행하던 중, DB에서 ROLE_ADMIN, ROLE_MANAGER로 바꾸어 주었는데도 403에러가 떠서 질문드립니다.

<SecurityConfig>

package com.example.SpringSecurity.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
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.configurers.AbstractHttpConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity // 스프링 시큐리티 필터가 스프링 필터체인에 등록이 됨.
@EnableMethodSecurity(securedEnabled = true)
public class SecurityConfig {

@Bean
public BCryptPasswordEncoder encodePwd(){
return new BCryptPasswordEncoder();
}

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf(AbstractHttpConfigurer::disable) // 사이트 위변조 요청 방지
.authorizeHttpRequests((authorizeRequests) -> { // 특정 URL에 대한 권한 설정.
authorizeRequests.requestMatchers("/user/**").authenticated();
authorizeRequests.requestMatchers("/manager/**")
.hasAnyRole("ADMIN", "MANAGER"); // ROLE_은 붙이면 안 된다. hasAnyRole()을 사용할 때 자동으로 ROLE_이 붙기 때문이다.
authorizeRequests.requestMatchers("/admin/**")
.hasRole("ADMIN"); // ROLE_은 붙이면 안 된다. hasRole()을 사용할 때 자동으로 ROLE_이 붙기 때문이다.
authorizeRequests.anyRequest().permitAll();
})

.formLogin((formLogin) -> {
formLogin
.loginPage("/loginForm") // 권한이 필요한 요청은 해당 url로 리다이렉트
.loginProcessingUrl("/login") // login 주소가 호출되면 시큐리티가 낚아채서 대신 로그인을 해준다.
.defaultSuccessUrl("/"); //로그인 성공시 /주소로 이동

})
.build();
}
}

 

<IndexController>

 

package com.example.SpringSecurity.controller;

import com.example.SpringSecurity.model.User;
import com.example.SpringSecurity.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class IndexController {

@Autowired private UserRepository userRepository;
@Autowired private BCryptPasswordEncoder bCryptPasswordEncoder;

@GetMapping({"/",""})
public String index(){
return "index";
}

@GetMapping("/user")
public @ResponseBody String user(){
return "user";
}

@GetMapping("/admin")
public @ResponseBody String admin(){
return "admin";
}

@GetMapping("/manager")
public @ResponseBody String manager(){
return "manager";
}

@GetMapping("/loginForm")
public String loginForm(){
return "loginForm";
}

@GetMapping("/joinForm")
public String joinForm(){
return "joinForm";
}

@PostMapping("/join")
public String join(User user){
System.out.println(user);
user.setRole("ROLE_USER");
String rawPassword = user.getPassword();
String encPassword = bCryptPasswordEncoder.encode(rawPassword);
user.setPassword(encPassword);
userRepository.save(user); // 패스워드가 암호화가 안되어있으면, 회원가입은 잘되나 Security를 이용해 로그인 할 수 없다.
return "redirect:/loginForm";
}

@GetMapping("/info")
public @ResponseBody String info(){
return "개인정보";
}
}

 

코드는 이러합니다. SecurityConfig는 v6이어서 수정하였습니다. 에러 해결에 도움 부탁드려요,,

항상 좋은 강의 감사합니다!

spring spring-security

Answer 2

0

kim1234123

해결하셨나요? 저도 똑같은 문제가 생겨서요..

0

communityai8509

안녕하세요, 인프런 AI 인턴이에요.

403 에러는 클라이언트가 서버에 접근하는 것을 거부된 상태를 의미합니다. 이 경우에는 접근 권한에 대한 설정에 문제가 있을 수 있습니다.

Spring Security에서 접근 권한을 설정하는 부분을 확인해보셔야 합니다. SecurityConfig 클래스에서 authorizeRequests 메서드를 사용하여 접근 권한을 설정하고 계시군요.

해당 코드만으로는 정확히 어떤 접근 권한이 필요한지 알 수 없지만, 아마도 ROLE_ADMINROLE_MANAGER 권한을 가진 사용자만 접근 가능한 페이지일 것으로 예상됩니다.

따라서, authorizeRequests 메서드 내부에 적절한 매칭 조건과 접근 권한 설정을 해주셔야 합니다. 예를 들어, 아래와 같이 설정해볼 수 있습니다.

.authorizeRequests()
    .antMatchers("/admin/**").hasRole("ADMIN")
    .antMatchers("/manager/**").hasRole("MANAGER")
    .anyRequest().authenticated()

위 코드는 /admin으로 시작하는 URL은 ROLE_ADMIN 권한을 가진 사용자만 접근할 수 있고, /manager로 시작하는 URL은 ROLE_MANAGER 권한을 가진 사용자만 접근할 수 있도록 설정한 예시입니다.

만약 매칭 조건이나 권한 설정이 잘못되었다면, 403 에러가 발생할 수 있으니 해당 부분을 다시 확인해보시고 수정해보세요. 그리고 수정 후에는 서버를 재시작하는 것도 잊지 마세요.

혹시 이 내용으로도 문제가 해결되지 않으면, 좀 더 코드를 자세히 살펴봐야 할 것 같습니다. 추가적인 정보를 알려주시면 더 도움을 드릴 수 있을 것 같아요.

JWT를 구현한 다음 이 API를 호출해서 사용하는 것은 프론트엔드 쪽에서 하는 역할인가요?

0

96

1

Jwt쓰면 스프링시큐리티는 필수적으로 사용해야하나요?

0

401

1

13:23 system.out 출력문이 다르게 나옵니다.

0

130

1

수료증 문의

0

226

2

9분대에 질문이 있습니다 !

0

114

1

password 비교를 하지 않았는데 어떻게 인증이 통과된 건가요?

0

321

1

이전 강의 참고하라는 말씀

0

253

1

강의 실습하다가 막히는 분들 참고(2024년8월 기준)

2

1116

2

구글 소셜 로그인 302

0

200

1

오류 문의 _ org.springframework.orm.jpa.JpaSystemException: could not deserialize

1

584

1

[자바] 시큐리티 Config 참고

13

953

1

이론강의

0

280

1

SpringSecurity JWT 로그인 URL 2개 설정하는 방법

0

487

1

2024.06기준) 최근 SecurityConfig 설정 문의

0

921

3

구글 로그인시 authentication이 null 값이라고 에러가 발생합니다.

0

678

2

특정 url필터 거는 방법 이슈

0

422

1

강사님께서 말씀하시는 시큐리티세션이 SecurityContext인가요?

0

277

1

25강 마지막 테스트에서 오류

1

1044

2

jwt를 저장하는 위치에 궁금한 점이 있습니다.

0

298

1

mustache를 사용하지 않고 thymeleaf를 사용하려고 하는데

0

697

1

세션 인증방식이 REST 원칙에 위배되는 건가요?

0

340

1

jwt와 실제데이터의 관계

1

243

1

jwt 와 세션ID의 관계

1

313

1

SecurityConfig에서 세션 설정, 인가 설정

0

421

1