Spring Boot 공부 일기 <12> - 인증, 인가

이동휘·2024년 8월 22일

Spring Boot

목록 보기
12/21

1. IDE

Intellij

2. 오늘 공부 내용

인증(Authentication)

  • 인증(Authentication) - 사용자가 누구인지 확인하는 과정

인증 과정

  1. 사용자 입력: 사용자가 사용자명과 비밀번호를 입력합니다.
  2. 인증 처리: 입력된 사용자명과 비밀번호를 기반으로 인증이 수행됩니다.
  3. 결과: 인증이 성공하면 사용자의 신원을 나타내는 Authentication 객체가 생성되고, 실패하면 에러가 발생합니다.

spring boot에서의 인증 설정

  • AuthenticationManager, UserDetailsService, PasswordEncoder 통해 관리
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("user").password("{noop}password").roles("USER")
            .and()
            .withUser("admin").password("{noop}admin").roles("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().authenticated() // 모든 요청에 대해 인증 필요
                .and()
            .formLogin() // 폼 기반 로그인 사용
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }
}

인가(Authorization)

  • 인가(Authorization) - 사용자가 애플리케이션의 특정 리소스나 기능에 접근할 수 있는 권한이 있는지를 결정하는 과정

역할 기반 인가 (Role-Based Access Control, RBAC)

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .antMatchers("/admin/**").hasRole("ADMIN") // ADMIN 역할만 접근 가능
            .antMatchers("/user/**").hasAnyRole("USER", "ADMIN") // USER와 ADMIN 역할 접근 가능
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .permitAll()
            .and()
        .logout()
            .permitAll();
}

메서드 수준의 인가 -@EnableGlobalMethodSecurity

@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
}

@Service
public class MyService {

    @PreAuthorize("hasRole('ADMIN')")
    public void adminOnlyFunction() {
        // ADMIN 역할만 접근 가능
    }

    @PreAuthorize("hasRole('USER')")
    public void userFunction() {
        // USER 역할만 접근 가능
    }
}

JWT 기반 인증과 인가

JWT 기반 인증과 인가

  1. 사용자 로그인: 사용자가 로그인하면 서버는 JWT를 생성하여 클라이언트에게 반환합니다.
  2. 클라이언트 저장: 클라이언트는 JWT를 로컬 스토리지나 쿠키에 저장합니다.
  3. 요청 시 토큰 전송: 클라이언트는 이후 요청마다 JWT를 Authorization 헤더에 포함하여 서버에 전송합니다.
  4. 토큰 검증: 서버는 요청을 받을 때마다 JWT를 검증하고, 유효한 경우 해당 사용자를 인증된 사용자로 처리합니다.

JWT 설정 예제

public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain)
                                    throws ServletException, IOException {
        String jwt = getJwtFromRequest(request);

        if (StringUtils.hasText(jwt) && validateToken(jwt)) {
            Long userId = getUserIdFromJWT(jwt);
            UserDetails userDetails = userDetailsService.loadUserByUsername(userId);
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                    userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }

        filterChain.doFilter(request, response);
    }
}

0개의 댓글