네로개발일기

개발자 네로의 개발 일기, 자바를 좋아합니다 !

'전체 글'에 해당되는 글 194건


반응형

대부분의 시스템에서는 회원 관리를 하고 있고, 그에 따른 인증(Authentication)과 인가(Authorization)에 대한 처리를 해줘야 한다. Spring에서는 Spring Security라는 별도의 프레임워크에서 관련된 기능을 제공하고 있다.

 

1. Spring Security

Spring 기반의 애플리케이션의 보안(인증과 권한, 인가 등)을 담당하는 스프링 하위 프레임워크다. Spring Security는 인증과 권한에 대한 부분을 Filter 흐름에 따라 처리하고 있다. Filter는 Dispatcher Servlet으로 가기 전에 적용되므로 가장 먼저 URL 요청을 받지만, Interceptor는 Dispatcher와 Controller 사이에 위치한다는 점에서 적용 시기의 차이가 있다. Spring Security는 보안과 관련해서 체계적으로 많은 옵션을 제공해준다.

 

[ 인증(Authentication)과 인가(Authorization) ]

- 인증(Authentication): 해당 사용자가 본인이 맞는지를 확인하는 절차

- 인가(Authorization): 인증된 사용자가 요청한 자원에 접근가능한지를 결정하는 절차

- 인증 성공 후 인가가 이루어 진다.

 

Spring Security는 기본적으로 인증 절차를 거친 후에 인가 절차를 진행하게 되며, 인가 과정에서 해당 리소스에 대한 접근 권한이 있는지 확인하게 된다. Spring Security에서는 이러한 인증과 인가를 위해 Principal을 아이디로, Credential을 비밀번호로 사용하는 Credential 기반의 인증 방식을 사용한다.

- Principal(접근 주체): 보호받는 Resource에 접근하는 대상

- Credential(비밀 번호): Resource에 접근하는 대상의 비밀번호

 

2. Spring Security 모듈

- SpringContextHolder

보안 주체의 세부 정보를 포함하여 응용프로그램의 현재 보안 컨텍스트에 대한 세부 정보가 저장된다. SecurityContextHolder는 기본적으로 SecurityContextHolder.MODE_INHERITABLETHREDLOCAL 방법과 SecurityContextxHolder.MODE_THREADLOCAL 방법을 제공한다.

 

- SecurityContext

Authentication을 보관하는 역할을 하며, SecurityContext를 통해 Authentication 객체를 가져올 수 있다.

 

- Authentication

현재 접근하는 주체의 정보와 권한을 담은 인터페이스이다. Authentication 객체는 Security Context에 저장되며, SecurityContextHolder를 통해 SecurityContext에 접근하고, SecurityContext를 통해 Authentication에 접근할 수 있다.

public interface Authentication extends Principal, Serializable {
    
    // 현재 사용자의 권한 목록을 가져옴
    Collection<? extends GrantedAuthority> getAuthorities();
    
    // credential(주로 비밀번호)을 가져옴
    Object getCredentials();
    
    Object getDetails();
    
    // Principal 객체를 가져옴
    Object getPrincipal();
    
    // 인증 여부를 가져옴
    boolean isAuthenticated();
    
    // 인증 여부를 설정함
    void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException;
}

 

- UsernamePasswordAuthenticationToken

Authentication을 implements한 AbstractAuthenticationToken의 하위 클래스로 User의 ID가 Principal 역할을 하고, Password가 Credential의 역할을 한다. UsernamePasswordAuthenticationToken의 첫 번째 생성자는 인증 전의 객체를 생성하고, 두 번째 생성자는 인증이 완료된 객체를 생성한다.

public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationToken {
    
    // 주로 사용자의 ID
    private final Object principal;
    
    // 주로 사용자의 password
    private Object credentials;
    
    // 인증 완료 정의 객체 생성
    public UsernamePasswordAuthenticationToken(Object principal, Object credentials) {
        super(null);
        this.principal = principal;
        this.credentials = credentials;
        this.setAuthenticated(false); // super.setAuthenticated(false);
    }
    
    public UsernamePasswordAuthenticationToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        this.credentials = credentials;
        supter.setAuthenticated(true);
    }
    
    // .. 생략 ..
}

public abstract class AbstractAuthenticationToken implements Authentication, CredentialsContainer {
}

 

- AuthenticationProvider

실제 인증에 대한 부분을 처리하는데, 인증 전의 Authentication 객체를 받아서 인증이 완료된 객체를 반환하는 역할을 한다. 아래와 같은 AuthenticationProvider 인터페이스를 구현해서 Custom한 AuthenticationProvider을 작성해서 AuthenticationManager에 등록하면 된다.

public interface AuthenticationProvider {
    
    // 인증 전의 Authentication 객체를 받아서 인증된 Authentication 객체를 반환
    Authentication authenticate(Authentication var1) throws AuthenticationException;
    
    boolean supports(Class<?> var1);
}

 

- AuthenticationManager

인증에 대한 부분은 AuthenticationManager를 통해 처리하는데 실질적으로는 AuthenticationManager에 등록된 AuthenticationProvider에 의해 처리된다. 인증에 성공하면 2번째 생성자를 이용해 인증이 성공한 (isAuthenticated = true) 객체를 생성하여 SecurityContext에 저장한다. 인증 상태를 유지하기 위해 세션에 보관하며, 인증이 실패한 경우에는 AuthenticationException을 발생시킨다.

public interface AuthenticationManager {
    
    Authentication authenticate(Authentication authentication) throws AuthenticationException;
}

AuthenticationManager를 implements한 ProviderManager는 실제 인증 과정에 대한 로직을 가지고 있는 AuthenticationProvider를 List로 가지고 있으며, ProviderManager는 loop를 통해 모든 provider를 조회하면서 authenticate 처리를 한다.

 

- UserDetails

인증에 성공하여 생성된 UserDetails는 Authentication 객체를 구현한 UsernamePasswordAuthenticationToken을 생성하기 위해 사용된다. UserDetails 인터페이스를 살펴보면 아래와 같이 정보를 반환하는 메서드를 가지고 있다. UserDetails 를 implements 하여 처리할 수 있다.

public interface UserDetails extends Serializable {

    Collection<? extends GrantedAuthority> getAuthorities();
    
    String getPassword();
    
    String getUsername();
    
    boolean isAccountNotExpried();
    
    boolean isAccountNonLocked();
    
    boolean isCrendentailsNotExpired();
    
    boolean isEnabled();
}

 

- UserDetailsService

UserDetails 객체를 반환하는 단 하나의 메서드를 가지고 있는데 일반적으로 UserRepository에서 주입하여 DB와 연결하여 처리한다.

public interface UserDetailsService {

    UserDetails loadUserByUsername(String var1) throws UsernameNotFoundException
}

 

- PasswordEncoding

AuthenticationManagerBuilder.userDetailsService().passwordEncoder()를 통해 패스워드 암호화에 사용될 PasswordEncoder 구현체를 지정할 수 있다.

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
	auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}

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

 

- GrantedAuthority

GrantAuthority는 현재 사용자(principal)가 가지고 있는 권한을 의미한다. ROLE_ADMIN이나 ROLE_USER와 같이 ROLE_*의 형태로 사용하며, 보통 "roles"라고 한다. GrantedAuthority 객체는 UserDetailsService에 의해 불러올 수 있고, 특정 자원에 대한 권한이 있는지를 검사하여 접근 허용 여부를 결정한다.

 

 출처 

https://mangkyu.tistory.com/76

 

[SpringBoot] Spring Security란?

대부분의 시스템에서는 회원의 관리를 하고 있고, 그에 따른 인증(Authentication)과 인가(Authorization)에 대한 처리를 해주어야 한다. Spring에서는 Spring Security라는 별도의 프레임워크에서 관련된 기능

mangkyu.tistory.com

 

728x90
반응형
blog image

Written by ner.o

개발자 네로의 개발 일기, 자바를 좋아합니다 !

반응형
kill -9로 종료하는 것은 좋지않다. jvm shutdown hook 또는 spring의 @PreDestroy의 실행을 보장하기 힘들다. kill -2(SIGINT) 혹은 kill -15(SIGTERM)을 쓰는 것이 좋다.

kill 명령어와 Graceful Shutdown에 대해서 알아보고자 한다.

 

 kill 명령어 알아보기 

https://frogand.tistory.com/69

 

[Linux] ps 명령어 / kill 명령어 / 프로세스 확인 및 죽이기 / 프로세스 일괄 종료 / kill process

# 프로세스란? 실행중인 프로그램 # ps 명령어 - Process 와 관련 linux 명령어는 ps 입니다. 옵션 기능 -e 시스템 상의 모든 프로세스 정보를 출력 -f 상세한 정보를 출력 (full-format) $ ps -ef UID PID PPID C..

frogand.tistory.com

 

애플리케이션 구동도 중요하지만, 안전한 종료야 말로 신규 버전을 배포하기 위해 필수적으로 진행해야 한다. 

 

Graceful Shutdown이란?

프로그램이 종료될 때, 최대한 side effect없이 로직을 잘 처리하고 종료하는 것을 의미한다.

지속가능한 소프트웨어를 위해 폐기 가능한(Disposability) 시스템을 구성해야 한다. 그리고 소프트웨어의 안전성을 높이기 위하여 graceful shutdow이 필요하다. 프로세스가 갑작스러운 하드웨어 문제에 의해 죽는 상황이 발생하더라도 문제가 없는 견고한 프로그램을 만들어야 한다. 프로그래머는 이를 준비해야 한다. (The Twelve-Factor App 방법론)

 

SIGTERM, SIGKILL 차이점

kill -9 $PID는 강제종료이다. -9인 SIGKILL은 리소스를 정리하는 핸들러를 지정하지 않고 프로세스를 바로 죽인다는 의미이다. 만약, 실행 중인 쓰레드가 있더라도 이를 무시하고 중단하는데 혹시라도 굉장히 중요한 작업중이라면 최악의 상황이 일어날 수 있기 때문이다.

 

 

Spring boot에서는 actuator를 사용해서 graceful shutdown을 할 수 있다.

 

 참고자료 

https://blog.marcosbarbero.com/graceful-shutdown-spring-boot-apps/

 

Graceful Shutdown Spring Boot Applications

This guide walks through the process of graceful shutdown a Spring Boot application. The implementation of this blog post is originally created by Andy Wilkinson and adapted by me to Spring Boot 2. The code is based on this GitHub comment. Introduction A l

blog.marcosbarbero.com

https://heowc.dev/2018/12/27/spring-boot-graceful-shutdown/

 

Spring Boot - 안전하게 종료시키기 | 허원철의 개발 블로그

Spring Boot를 안전하게 종료시키는 방법에 대한 소개이다.

heowc.dev

https://kapentaz.github.io/spring/Spring-Boot-Actuator-Graceful-Shutdown/#

 

Spring Boot Actuator Graceful Shutdown

Spring Boot 환경에서 application을 shutdown 하는 방법 중 대표적인 것이 actuator의 shutdown endpoint 기능을 이용하는 것입니다. 이 endpoint는 예상과 달리 처리 중인 요청이 있더라도 그냥 shutdown 처리를 합니

kapentaz.github.io

 

728x90
반응형
blog image

Written by ner.o

개발자 네로의 개발 일기, 자바를 좋아합니다 !

반응형

https://www.amcharts.com

 

JavaScript charting library - amCharts 4

The most innovative charting library on the market. Easily add stunning data visualizations to JavaScript, TypeScript, Angular, React, and other apps.

www.amcharts.com

 

Demo에 가보면 예제를 볼 수 있다.

그 중에서 나는 column-with-rotated-series를 사용하였다.

 

 

ajax로 데이터를 가져와서 Chart를 뿌려주는 것을 만들려고 한다.

 

data 형식은 아래와 같다.

var data = [
  {category: "USA", value: 2025}, 
  {category: "China", value: 1882}, 
  {category: "Japan", value: 1809}, 
	... 생략 ... 
  {category: "Germany", value: 1322}];

 

column-chart.js

var ColumnChart = function () {
  this.initEvents();
}

ColumnChart.prototype.initEvents = function () {

}

ColumnChart.prototype.getData = function (url, id) {
  var _this = this;

  $.ajax({
    url: url,
    method: "GET",
    dataType: "json",
    async: false,
    success: function(data) {
      _this.renderChart(id, data)
    },
    error: function(err) {
      alert("적용 중 에러가 발생하였습니다.");
      console.log(err);
    }
  });
}

ColumnChart.prototype.renderChart = function (chartId, data) {
  var root = am5.Root.new(chartId);

  root.setThemes([
    am5themes_Animated.new(root)
  ]);

  var chart = root.container.children.push(
    am5xy.XYChart.new(root, {
      panX: false,
      panY: false,
      layout: root.verticalLayout
    })
  );

  // y좌표 설정
  var yRenderer = am5xy.AxisRendererY.new(root, {});
  yRenderer.labels.template.setAll({
    fontSize: 13 // y좌표 폰트 크기 조정
  });

  var yAxis = chart.yAxes.push(
    am5xy.ValueAxis.new(root, {
      renderer: yRenderer
    })
  );

  // x좌표 설정
  var xRenderer = am5xy.AxisRendererX.new(root, { minGridDistance: 30 });
  xRenderer.labels.template.setAll({
    centerY: am5.p10,
    centerX: am5.percent(50),
    paddingRight: 0,
    fontSize: 13 // x좌표 폰트 크기 조정
  });

  var xAxis = chart.xAxes.push(am5xy.CategoryAxis.new(root, {
    maxDeviation: 0.3,
    categoryField: "category", // 카테고리 명을 적어주면 된다.
    renderer: xRenderer,
  }));

  xAxis.data.setAll(data);

  var tooltip = am5.Tooltip.new(root, {
    labelText: "{valueY}",
    autoTextColor: false // 문자 색상을 설정할 수 있다. autoTextColor: false로 색상 설정을 없앰.
  });

  var series = chart.series.push(
    am5xy.ColumnSeries.new(root, {
      name: "Chart Name",
      xAxis: xAxis,
      yAxis: yAxis,
      valueYField: "value",
      categoryXField: "category", // x좌표 categoryField와 일치시킨다.
      tooltip: tooltip
    })
  );

  series.columns.template.setAll({
    cornerRadiusTL: 5,
    cornerRadiusTR: 5,
    width: 32 // 컬럼의 너비 설정
  });

  // 컬럼 색상 설정 -> 기본으로 설정
  series.columns.template.adapters.add("fill", function (fill, target) {
    return chart.get("colors").getIndex(series.columns.indexOf(target));
  });
  series.columns.template.adapters.add("stroke", function (stroke, target) {
    return chart.get("colors").getIndex(series.columns.indexOf(target));
  });

  series.data.setAll(data);
  chart.set("cursor", am5xy.XYCursor.new(root, {}));
}

 

index.html

<div class="category-chart">
 <div class="row">
  <div class="box">
   <div class="category-name">Category</div>
   <div id="category-chart" class="chart"></div>
  </div>
 </div>
</div>

<script src="https://cdn.amcharts.com/lib/5/index.js"></script>
<script src="https://cdn.amcharts.com/lib/5/xy.js"></script>
<script src="https://cdn.amcharts.com/lib/5/themes/Animated.js"></script>
<script>
    var ColumnChart = new ColumnChart();

    $(function () {
      ColumnChart.getData('/category', 'category-chart'); // ajax로 data를 가져와 chart를 그려준다.
    })
</script>

 

chart.css

.category-chart {
  width: 100%;
}

.box {
  /* width: 48%; */
  background-color: rgba(238, 238, 238, 0.4);
  padding-top: 20px;
  padding-bottom: 16px;
  margin-left: auto;
  margin-bottom: 20px;
  border-radius: 10px;
}

.category-name {
  font-weight: bold;
  text-align: center;
  margin-bottom: 6px;
}

.chart {
  height: 300px; /* height를 꼭 지정해주어야 한다. */
}

 

 

728x90
반응형
blog image

Written by ner.o

개발자 네로의 개발 일기, 자바를 좋아합니다 !

반응형

Kaminari를 이용한 Pagination 구현

1. Gem 설치

Gemfile 작성

Gem 'kaminari'
$ bundle install

2. Controller에서 내용 추가

class PostsController < ApplicationController
    def index
        @posts = Post.order("created_at DESC").page params[:page]
    end
end

3. 한 목록당 게시물 갯수 설정

class Post < ApplicationRecord 
    paginates_per 5
    ...
end

혹은

class PostsController < ApplicationController
    def index
        @posts = Post.order("created_at DESC").page(params[:page]).per(5)
    end
    
    def show
        @posts = Post.page(params[:page]).per(10)
    end
end

이런 식으로 paginate 정의를 해준다.

 

index.html.erb 파일에서 아래 태그를 삽입하면 목록 번호가 뜬다.

<%= paginate @posts %>

 

kaminari에 디자인 템플릿 적용

https://github.com/felipecalvo/bootstrap5-kaminari-views

 

GitHub - felipecalvo/bootstrap5-kaminari-views: Bootstrap 5 compatible styles for Kaminari. Tested on Bootstrap 5.0.1.

Bootstrap 5 compatible styles for Kaminari. Tested on Bootstrap 5.0.1. - GitHub - felipecalvo/bootstrap5-kaminari-views: Bootstrap 5 compatible styles for Kaminari. Tested on Bootstrap 5.0.1.

github.com

kaminari에 디자인 템플릿을 적용할 수 있다.

728x90
반응형
blog image

Written by ner.o

개발자 네로의 개발 일기, 자바를 좋아합니다 !

반응형

스프링을 이해하려면 POJO 기반으로 스프링 삼각형이라는 애칭을 가진 IoC/DI, AOP, PSA라고 하는 스프링의 3대 프로그래밍 모델에 대해 이해가 필수다.

 

IoC/DI - 제어의 역전/의존성 주입

프로그래밍에서 의존성이란 무엇일까?

예를들어) 운전자가 자동차를 생성한다. -> 자동차가 내부적으로 타이어를 생산한다. (운전자 -> 자동차 -> 타이어) 의존

-> 전체(의존하는 객체)가 부분(의존되는 객체)에 의존한다.

 

집합(Aggregation) 관계: 부분이 전체와 다른 생명 주기를 가질 수 있다.

구성(Composition) 관계: 부분은 전체와 같은 생명 주기를 갖는다.

interface Tire {
    String getBrand();
}

public class KoreaTire implements Tire {
    public String getBrand() {
        return "한국 타이어";
    }
}

public class AmericaTire implements Tire {
    public String getBrand() {
        return "미국 타이어";
    }
}

public class Car {
    
    Tire tire;
    
    public Car() {
        tire = new KoreaTire(); // Car 클래스는 Tire 인터페이스 뿐만 아니라 KoreaTire 클래스도 의존하게 된다.
    }
    
    public String getTireBrand() {
        return "장착된 타이어: " + tire.getBrand();
    }

 

1. 생성자 주입

public class Car {
    Tire tire;
    
    public Car(Tire tire) { // 생성자 주입
        this.tire = tire;
    }
    
    public String getTireBrand() {
        return "장착된 타이어: " + tire.getBrand();
    }
}

public class Driver {
    public static void main(String[] args) {
        Tire tire = new KoreaTire();
        
        Car car = new Car(tire);
        
        System.out.println(car.getTireBrand());
    }
}

의존성 주입을 이용함으로써 자동차가 구체적인 객체를 생성하고 연결하는 것이 아니라 운전자가 대신 원하는 의존성을 생성하고 연결해준다.

 

따라서, Car 객체는 의존성 주입을 통해 추상적인 인터페이스에 의존하면서 실행이 가능해진다. Car 객체는 수정없이 확장이 가능해진다.

 

생성자 주입 방식의 장점

- 의존 관계 설정이 되지 않으면 객체 생성 불가 -> 컴파일 타임에 인지 가능 NPE 방지

- 의존성 주입이  필요한 필드를 final로 선언하여 Immutable한 객체로 만들 수 있음

- 순환 참조 감지 기능 -> 순환 참조시 앱 구동 실패

- 테스트 코드 작성 용이 (독립적으로 인스턴스화가 가능한 POJO(Plain Old Java Object)여야 하는 것이다. DI 컨테이너를 사용하지 않고도 단위 테스트에서 인스턴스화할 수 있어야 한다.)

 

2. 속성 주입

@Autowired를 통한 의존성 주입

@Autowired Tire tire를 사용하여 설정자 메서드를 사용하지 않고도 스프링 프레임워크가 설정파일을 통해 설정자 메서드 대신 속성을 주입해준다.

 

@Resource를 통한 속성 주입

@Resource는 @Autowired와 같이 속성을 자동으로 엮어준다. @Autowired는 스프링의 어노테이션이고 @Resource는 자바표준 어노테이션이다.  

 

AOP - Aspect 관점 핵심 관심사 횡단 관심사

AOP - 관점지향 프로그래밍

스프링 DI가 의존성에 대한 주입이라면 AOP는 로직에 대한 주입이다.

 

여러 모듈에서 발생하는 공통적인 부분 -> 횡단 관심사

AOP 로직 주입이 가능한 부분

Around(메서드 전 구역), Before(메서드 시작 전), After(메서드 종료 후), After Returning(메서드 정상 종료 후), After Throwing (메서드에서 예외가 발생하면서 종료된 후)

 

스프링 AOP의 핵심

- 인터페이스 기반

- 프록시 기반

- 런타임 기반

 

PSA - 일관성 있는 추상화

서비스 추상화의 예로 JDBC를 들 수 있다. JDBC라고 하는 표준 스펙이 있기에 어떤 DBMS를 사용하든 Connection, Statement, ResultSet을 이용해 공통된 방식으로 코드 작성이 가능하다. 데이터베이스의 종류에 관계없이 같은 방식으로 제어할 수 있는 이유는 디자인패턴에서 설명했던 어댑터패턴을 활용했기 때문이다.

 

다수의 기술을 공통의 인터페이스로 제어할 수 있게 한 것 -> 서비스 추상화

스프링 프레임워크는 서비스 추상화를 위해 다양한 어댑터를 제공한다.

728x90
반응형
blog image

Written by ner.o

개발자 네로의 개발 일기, 자바를 좋아합니다 !