π 2024λ 02μ 01μΌ
55μΌμ°¨λ μ§κΈκΉμ§ λ°°μ΄κ²μ 볡μ΅ν λ΄μ©μ΄λ―λ‘ λ°λ‘ μ 리νμ§ μκ² μ΅λλ€.
- JWTprovider
@Component public class JWTprovider { public String createToken(String email, String role){ /* claims : ν΄λ μμ ν ν° μ¬μ©μμ λν μμ±μ΄λ λ°μ΄ν° ν¬ν¨, μ£Όλ‘ νμ΄λ‘λλ₯Ό μλ―Έ */ Claims claims = Jwts.claims().setSubject(email); claims.put("role",role); Date now = new Date(); Key key = Keys.hmacShaKeyFor("μ¬κΈ°κ°μν¬λ¦Ών€μΈλ°μ’κΈΈκ²μ€μ ν΄μΌν΄".getBytes(StandardCharsets.UTF_8)); return Jwts.builder() .setClaims(claims) // μ 보 μ μ₯ .setIssuedAt(now) .setExpiration(new Date(now.getTime() + 30 * 60 * 1000L)) .signWith( key, SignatureAlgorithm.HS256) .compact(); } }
- JwtAuthFilter
@Component public class JwtAuthFilter extends GenericFilter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { try { String bearerToken = ((HttpServletRequest) servletRequest).getHeader("Authorization"); if(bearerToken != null){ if(!bearerToken.startsWith("Bearer ")){ throw new AuthenticationServiceException("ν ν° νμμ΄ λ§μ§ μμ΅λλ€."); } Key key = Keys.hmacShaKeyFor("μ¬κΈ°κ°μν¬λ¦Ών€μΈλ°μ’κΈΈκ²μ€μ ν΄μΌν΄".getBytes(StandardCharsets.UTF_8)); String token = bearerToken.substring(7); // κ²μ¦ λ° ν΄λμμ€ μΆμΆ Claims claims = Jwts.parserBuilder() .setSigningKey(key) .build() .parseClaimsJws(token) .getBody(); // Authentication κ°μ²΄λ₯Ό μμ±νκΈ° μν UserDetails μμ± List<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority("ROLE_"+claims.get("role"))); UserDetails userDetails = new User(claims.getSubject(), "", authorities); Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); } filterChain.doFilter(servletRequest,servletResponse); }catch (AuthenticationServiceException e){ HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value()); httpServletResponse.setContentType("application/json"); httpServletResponse.getWriter().write(ResponseDTO.responseErrorMassage(HttpStatus.UNAUTHORIZED, e.getMessage()).toString()); } } }
- InitialDataLoader
@Component public class InitialDataLoader implements CommandLineRunner { // CommandLineRunnerλ₯Ό ν΅ν΄ μ€νλ§λΉμΌλ‘ λ±λ‘λλ μμ μ run λ©μλ μ€ν private final MemberRepository memberRepository; private final PasswordEncoder passwordEncoder; public InitialDataLoader( MemberRepository memberRepository, PasswordEncoder passwordEncoder ) { this.memberRepository = memberRepository; this.passwordEncoder = passwordEncoder; } @Override public void run(String... args) throws Exception { if(memberRepository.findByEmail("admin@test.com").isEmpty()){ Member adminMember = Member.builder() .name("admin") .email("admin@test.com") .password(passwordEncoder.encode("1234")) .role(Role.ADMIN) .build(); memberRepository.save(adminMember); } } }
- SecurityConfig
@Configuration @EnableWebSecurity //@EnableGlobalMethodSecurity(prePostEnabled = true) // 6.* λΆν°λ μλμΌλ‘ true μ€μ public class SecurityConfig { private final JwtAuthFilter jwtAuthFilter; @Autowired public SecurityConfig(JwtAuthFilter jwtAuthFilter) { this.jwtAuthFilter = jwtAuthFilter; } @Bean public PasswordEncoder passwordEncoder(){ return PasswordEncoderFactories.createDelegatingPasswordEncoder(); } @Bean public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception{ return httpSecurity .csrf(AbstractHttpConfigurer::disable) // 6.* λΆν°λ csrf() μ΄ μ¬λΌμ§λ€. .cors(cors -> cors.configurationSource(CorsConfig.corsConfigurationSource())) .httpBasic(AbstractHttpConfigurer::disable) // μ μ URL μ€μ .authorizeHttpRequests(authorizeRequest -> authorizeRequest .requestMatchers( "/", "api/member/create", "api/doLogin", "api/items", "api/item/image/**", "api/login", "/login" ) .permitAll() /* ROLE_μ λΆμ΄λ©΄ μ λλ€. hasAnyRole()μ μ¬μ©ν λ μλμΌλ‘ ROLE_μ΄ λΆκΈ° λλ¬Έμ΄λ€. */ .requestMatchers("/manager/**") .hasAnyRole("ADMIN") .anyRequest() .authenticated() ) .sessionManagement((sessionManagement) -> sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS) ) .formLogin((formLogin) -> { /* κΆνμ΄ νμν μμ²μ ν΄λΉ urlλ‘ λ¦¬λ€μ΄λ νΈ */ // formLogin.loginPage("/login"); }) .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class) .build(); } }
ν΄λμ€λͺ μ€λͺ JWTprovider JWT ν ν°μ μμ±νλ ν΄λμ€ JwtAuthFilter JWT ν ν°μ κ²μ¦νκ³ μ¬μ©μ μΈμ¦μ μ²λ¦¬νλ νν° InitialDataLoader μ ν리μΌμ΄μ μμ μ μ΄κΈ° λ°μ΄ν°λ₯Ό λ‘λνλ ν΄λμ€ SecurityConfig Spring Security μ€μ μ λ΄λΉνλ ν΄λμ€
λμ€μ λ€μ μ 리ν κ².