CSRF, JWT 토큰

IT 2020. 7. 29. 15:09

csrf 는 웹서비스에서 cross-site-request-forgery를 막기위해

백엔드에서 토큰을 발행하고 프론트엔드에서 이를 사용하여 최종적으로는 유효한 요청인지를 확인하는 방식.

 

 

JWT토큰은 인증에 사용되는 방식으로서 REF

OAuth와 연동해서 사용할 수도 있고 독립적으로 사용할 수도 있다.

 

 OAuth1과 OAuth2의 가장 큰 차이는 OAuth2의 경우 refresh 토큰이 가능. 

 

 

 

JWT를 구현하면서 마주치게 되는 고민들

최근 모바일, 웹 등 다양한 환경에서 서버와 통신하면서 많은 사람들이 JWT 토큰 인증 방식을 추천합니다. 이 포스팅에서는 JWT를 이해하고 구현하면서 마주치게 되는 고민들에 대해 정리해보려 �

swalloow.github.io

 

Posted by yongary
,

spring boot2에서부터는  controller에서 @Async에서도

completableFuture를 리턴할 수 있다..

( 그 전에도 Async와 EnableAsync는 있었는데 completableFuture를 리턴하지는 못한것 같은데, 확인 중)

 

<사전지식>

1. Future(Java5 에 등장) 와 Observable간에 전환.  (마찬가지로 CompleatbleFuture와  Single간에 전환도 유사)

Observable<String> source = Observable.fromFuture(future);

source.subscribe(System.out::println);

 

2. Future vs CompletableFuture (Java8에 등장)  : ref
    CompletableFuture.complete() 함수를 호출해  Future를 수동으로 종료할 수 있음. 

    그 외 runAysnc, supplyAsync, thenApply, thenAccept, thenRun 등 함수들이 제공됨.

  

 


출처: https://12bme.tistory.com/570 [길은 가면, 뒤에 있다.]

 

[RxJava] RxJava 프로그래밍(1) - 리액티브 프로그래밍

서버 다수와 통신하게 되면 API 호출 각각에 콜백을 추가하게 된다. 콜백이 늘어나면 애플리케이션의 복잡성도 증가(callback hell)하게 된다. RxJava는 자바로 리액티브 프로그래밍을 할 수 있는 라이

12bme.tistory.com

https://12bme.tistory.com/570 

 

 

 

참고: https://howtodoinjava.com/spring-boot2/rest/enableasync-async-controller/#:~:text=1.-,Spring%20%40Async%20rest%20controller,application%20classes%20for%20asynchronous%20behavior.&text=The%20%40Async%20annotated%20methods%20can,result%20of%20an%20asynchronous%20computation.

 

Spring @Async rest controller example - Spring @EnableAsync

Spring @Async non blocking rest controller example. Learn to use spring async behavior with @EnableAsync annotation. Spring async completablefuture example.

howtodoinjava.com

 

Posted by yongary
,

Test Code 관련

springBoot gradle 2020. 7. 13. 17:19

 

 Stub/ Mock/Fake 등을 묶어‘테스트 더블(Test Double)' 이라고 한다. (여기서 Double=대역)

 

SpringBoot에선 BDDMockito를 지원해 B(Behavior) Driven Test를 지원한다.

 

 

MockMVC 과 Mockito의 차이.

- mockito가 좀 더 general하고 더 많은 case를 지원하고, 여러가지 mock도 지원한다. (mockObject.when()  등등...)

- MockMVC는 spring 전용.  

 

Posted by yongary
,

격리수준

BACK-END 2020. 7. 11. 22:15

DB의 트랜잭션은 ACID를 보장해야 한다. (참고: https://feco.tistory.com/45

 - 원자성, 일관석, 격리성, 지속성

Atomicity: 한트랜잭션이 여러query로 이루어질 수 있는데, 한 트랜잭션의 모든 query가 성공하거나, 혹은 part of transaction이 실패하면 전체 transaction이 실패/혹은 rollback해야한다. 
Consistency: 트랜잭션후에도 DB는 항상 valid state 를 유지해야 한다.(for각종 constraint들 enabled in DB)
Isolation : 동시에 여러개의 transaction이 실행되더라도 하나씩 고립되어 순차적으로 실행되어야한다.
Durability: 트랜잭션이 commit되고 나면, 항상 available해야한다. server가 꺼졌다 켜지더라도...

 

 

이중, "I"인 Isolation(격리성의) 수준은 (참고: https://m.blog.naver.com/PostView.nhn?blogId=blueaian&logNo=220636152759&proxyReferer=https:%2F%2Fwww.google.com%2F )

 

- READ UNCOMMITED (dirty read 발생가능 + 아래들)

   : 일반적인 Database에서는 사용하지 않음

- READ COMMITED (none-repeatable read 발생가능 + 아래 )

   : Oracle 트랜잭션 격리 수준 ( OLTP에서 많이 채택 )

   : commit된 데이터에 대해 다른 세션에서 읽을 수 있음

- REPEATABLE READ  (Phantom Read발생가능)

  : Mysql 기본 격리수준

  : select 에 대해서도 MVCC 수준 유지

- SERIALIZABLE

  : 동시성이 중요한 Database에서는 사용하지 않음

 

Posted by yongary
,

점을 V(Vertex)
edge를 E라고 하면..

 

처음에 V를 쭉 더해놓고

다음부터는 BFS (혹은 DFS도 가능)

 

따라서 complexity는 O (V + E) 

 

https://www.geeksforgeeks.org/detect-cycle-undirected-graph/

cycle find 코드예제:

더보기
import java.util.*;

class Graph {
    private int V;
    private LinkedList<Integer>[] adj;

    Graph(int v) {
        V = v;
        adj = new LinkedList[v];
        for (int i = 0; i < v; ++i)
            adj[i] = new LinkedList();
    }

    void addEdge(int v, int w) {
        adj[v].add(w);
        adj[w].add(v);
    }

    boolean isCyclicUtil(int v, boolean[] visited, int parent) {
        visited[v] = true;
        for (Integer i : adj[v]) {
            if (!visited[i]) {
                if (isCyclicUtil(i, visited, v))
                    return true;
            } else if (i != parent) {
                return true;
            }
        }
        return false;
    }

    boolean isCyclic() {
        boolean[] visited = new boolean[V];
        for (int i = 0; i < V; ++i)
            if (!visited[i])
                if (isCyclicUtil(i, visited, -1))
                    return true;

        return false;
    }
}

public class CycleDetectionExample {
    public static void main(String[] args) {
        Graph g1 = new Graph(5);
        g1.addEdge(1, 0);
        g1.addEdge(0, 2);
        g1.addEdge(2, 1);
        g1.addEdge(0, 3);
        g1.addEdge(3, 4);
        
        if (g1.isCyclic())
            System.out.println("Graph contains cycle");
        else
            System.out.println("Graph doesn't contain cycle");
    }
}

코드예제임.

 

Digikstra 알고리듬.  근접한 distance 부터 하나씩 추가하는 알고리듬.

더보기
import java.util.*;

class Node implements Comparable<Node> {
    int id;
    int distance;
    
    public Node(int id, int distance) {
        this.id = id;
        this.distance = distance;
    }
    
    @Override
    public int compareTo(Node other) {
        return Integer.compare(this.distance, other.distance);
    }
}

public class DijkstraAlgorithmWithClass {
    public static void dijkstra(int[][] graph, int start) {
        int n = graph.length;
        int[] distance = new int[n];
        Arrays.fill(distance, Integer.MAX_VALUE);
        distance[start] = 0;
        
        PriorityQueue<Node> pq = new PriorityQueue<>();
        pq.offer(new Node(start, 0));
        
        while (!pq.isEmpty()) {
            Node curr = pq.poll();
            int node = curr.id;
            int dist = curr.distance;
            
            if (dist > distance[node]) continue;
            
            for (int neighbor = 0; neighbor < n; neighbor++) {
                int weight = graph[node][neighbor];
                if (weight > 0 && distance[node] + weight < distance[neighbor]) {
                    distance[neighbor] = distance[node] + weight;
                    pq.offer(new Node(neighbor, distance[neighbor]));
                }
            }
        }
        
        // 출력: 각 노드까지의 최단 경로 길이
        System.out.println("Node\tDistance");
        for (int i = 0; i < n; i++) {
            System.out.println(i + "\t" + distance[i]);
        }
    }
    
    public static void main(String[] args) {
        int[][] graph = {
            {0, 4, 0, 0, 0, 0, 0, 8, 0},
            {4, 0, 8, 0, 0, 0, 0, 11, 0},
            // 나머지 그래프 데이터도 입력
        };
        
        dijkstra(graph, 0);
    }
}
Posted by yongary
,

간단한 @StreamListener  annotation만으로 stream 통신을 할 수 있으므로, MSA에서 유리하다.

 

https://coding-start.tistory.com/139

 

Kafka - Spring cloud stream kafka(스프링 클라우드 스트림 카프카)

Kafka - Spring cloud stream kafka(스프링 클라우드 스트림 카프카) 이전 포스팅까지는 카프카의 아키텍쳐, 클러스터 구성방법, 자바로 이용하는 프로듀서,컨슈머 등의 글을 작성하였다. 이번 포스팅은 �

coding-start.tistory.com

 

그 외에
 SpringCloud Eureka : MSA환경에서 서버들을 registry 해놓고, 로드밸런서와 같은 역할 가능.

 

 springcloud zuul : MSA환경에서 G/W를 이용해 token 체크등을 한 곳에서  모아서 할 수 있다.

 

 

 

Posted by yongary
,

Arrays (feat Stream)

java8~ 2020. 7. 4. 20:41

1. Arrays.stream     

 

int[] arr = new int[] { 3, 5, 8} 

Arrays.stream( arr).filter(x -> x <=5).sum();

 

==> 근데 딱 한군데, arr -> List로 바꿀때는 잘 안됨.

List<Integer> list = IntStream.of(arr).boxed().collect(Collectors.toList())

           (boxed()가 primitive array를 단일 element로 잘라 줌)

 

참고: Stream<String> st = Stream.of("A", "B","C"); 등  다양한 Stream생성 방식:  https://codechacha.com/ko/stream-creation/

 

2. Arrays.sort 

int[][] arr = new int[][]{ {1,2,3} {4,5,2}}

Arrays.sort(arr,  (a, b) -> (a[2] - b[2]) ) ;   //Comparator를 functional로 바로 넣음..

3. Arrays.binSearch (arr, target)

  -> 찾으면 idx리턴, 못 찾으면 들어갈 자리  -idx-1 리턴..  :항상 음수를 리턴하기 위해..


 

====stream 통계=====


min/max/avg 등을 한꺼번에 구할때..

DoubleSummaryStatistics stat =  arr.stream().mapToDouble(x -> x).summaryStatistics();


stat = {counnt:10.0, sum:120.0, min:1.0, aveerage:10.11, max:19.0}

 

 

Posted by yongary
,

 

기본적으로 설치해서  fabric-samples/fabcar/startFabric.sh 를 하면

 

/network.sh up createChannel -ca -s couchdb 로 실행이 된다,.

 

이 때

./organizations/peerOrganizations 를 참조하면서. (아래 3개 파일 이용)

    org1.example.com/fabric-ca-client-config.yaml*
    org1.example.com/connection-org1.json
    org1.example.com/connection-org1.yaml

 

 

노드1, 노드2를 물리적으로 분리할 경우 (https://www.slideshare.net/hlkug/201903-hyperledger-fabric)

<노드 1>
- 채널생성 (peer channel create),

- 채널Join  (peer channel join),

- Anchor Peer 업데이트 (peer channel update)

- 체인코드 설치(peer chaincode install),

- 체인코드 Instantiate(peer chaincode instantiate),

- 체인코드 Query(peer chaincode query)

<노드 2>

- 제네시스 Block Fetch (peer channel fetch 0...)

- 채널Join  (peer channel join),

- Anchor Peer 업데이트 (peer channel update) 

- 체인코드 설치(peer chaincode install),

- 체인코드 Query(peer chaincode query)

 

 

개인이 만든 fabric-starter.git 참고 (https://www.altoros.com/blog/deploying-a-multi-node-hyperledger-fabric-network-in-5-steps/ ) - 테스트 필요.

Posted by yongary
,

 

<spring 에서 fabric G/W를 이용한 컨트랙트 실행>

implementation 'org.hyperledger.fabric:fabric-gateway-java:2.0.0'  추가 후 아래소스 참조.

https://hyperledger.github.io/fabric-gateway-java/

 

 

 

<유저 생성 후 실행 example>

https://newtechstax.com/2019/11/12/integrating-fabric-blockchain-with-springboot-application/

Posted by yongary
,

CA는

- ID를 등록하고 LDAP과 연결해서 사용자 등록수행

- ECert 발행 (Enrollment Certi)

- Certi 갱신과 철회

 

CA_server와  CA_client로 구성.

<CA server>

$fabric-ca-server start -b <admin>:<adminpw>

 

<CA client>

$export FABRIC_CA_CLIENT_HOME=$HOME/fabric-ca/clients/admin 
$fabric-ca-client register --id.name admin2 --id.affiliation org1.department1 --id.attrs 'hf.Revoker=true,admin=true:ecert'

 

 

 

<참고 사이트>

https://hyperledger-fabric-ca.readthedocs.io/en/release-1.4/users-guide.html

 

Fabric CA User’s Guide — hyperledger-fabric-cadocs master documentation

This section describes how to configure the Fabric CA server to connect to PostgreSQL or MySQL databases. The default database is SQLite and the default database file is fabric-ca-server.db in the Fabric CA server’s home directory. If you don’t care about

hyperledger-fabric-ca.readthedocs.io

 

 

Posted by yongary
,