보안 인증 (JWT 인증)

    보안 인증 (JWT 인증)


    기사 요약

    JWT (JSON Web Tokens)는 암호화를 사용하여 데이터를 만드는 인터넷 표준 중의 하나입니다. JWT에 대한 보다 자세한 내용은 아래의 페이지를 통해 확인하시기 바랍니다.


    JWT 인증

    Secret Key를 이용하여 고객사의 서버에서 JWT 문자열을 만들어 인증하는 방식입니다. 대부분의 상황에서 권장하는 방식입니다.

    <script type="text/javascript" src="https://static.shoplive.cloud/shoplive.js"></script>
    <script>cloud.shoplive.init({ accessKey: 'YOUR ACCESS KEY HERE', userJWT: "USER_JWT" });</script>
    
    <!-- OR -->
    
    <script type="text/javascript" src="https://static.shoplive.cloud/shoplive.js"></script>
    <script>
      cloud.shoplive.init({ accessKey: 'YOUR ACCESS KEY HERE' });
      cloud.shoplive.setUserJWT("USER_JWT");
    </script>


    인증 토큰 생성 가이드

    Shoplive에서 사용하는 JWT payload는 다음과 같습니다.

    Property

    Description

    Sample

    Comment

    expiration

    (Required)

    만료 시간 (timestamp)

    1516239022

    토큰 만료 시간

    userId

    (Required)

    사용자 아이디

    sample_user_id

    로그인 사용자의 유일성을 보장할 수 있는 값

    name

    사용자 이름

    (채팅창에서 사용)

    닉네임

    이름을 지정하지 않을 경우 캠페인의 채팅 설정에 따라 채팅시 입력을 강제하도록 하거나 임의로 생성되도록 할 수 있습니다.

    gender

    사용자 성별

    빈 값(미지정), m(남), f(여)

    전체/로그인 시청자 데이터에서 확인할 수 있습니다.

    age

    사용자 나이

    25

    전체/로그인 시청자 데이터에서 확인할 수 있습니다.

    custom

    사용자 임의 데이터

    custom data

    최대 1KB까지 임의의 데이터를 세팅할 수 있습니다.

    전체/로그인 시청자 데이터에서 확인할 수 있습니다.

    userScore

    사용자 등급

    10

    사용자 등급을 세팅하면 등급에 따른 입장 제한, 이벤트 추첨 제한 등의 기준으로 사용할 수 있습니다.

    -100에서 100까지의 정수로 세팅할 수 있습니다.

    userType

    사용자 유형

    VIP

    방송 입장 제한(Entry Type)이 설정된 방송에 입장할 때, 해당 값을 참조하여 특정 유저(VIP)만 방송에 입장하도록 설정할 수 있습니다.

    profile

    사용자 프로필 이미지 URL

    https://image.shoplive.cloud/sample_profile.png

    방송의 채팅 목록에서 프로필 이미지를 표시할 때 이미지 경로를 직접 설정할 수 있습니다.

    권장되는 이미지 크기는 64px X 64px입니다. 이미지 파일 크기를 과도하게 증가시키지 않도록 주의하십시오.


    샘플 코드 (JWT 생성)

    import io.jsonwebtoken.JwtBuilder;
    import io.jsonwebtoken.Jwts;
    import io.jsonwebtoken.SignatureAlgorithm;
    import java.util.Date;
    public class JwtAuthorizationGeneratorSample {
        public static void main(String[] args) {
            /*
             * 암호화 알고리즘
             * 지원하는 알고리즘은 https://jwt.io/ 혹은 https://github.com/jwtk/jjwt 사이트를 참조하세요
             */
            String algorithm = "HS256";
            /*
             * 발급 받은 base64 인코딩된 secret key
             */
            String base64EncodedSecretKey = "ckFXaWtRWENtSTA2QnpGVmxWNlBySWF4cUk1Q1pxbHU=";
            /*
             * Set expiring time for JWT token as 12 hours
             */
            long expiration = System.currentTimeMillis() + 12 * (60 * 60 * 1000);
            // OR
            // long expiration = LocalDateTime.now().plus(12, ChronoUnit.HOURS).atZone(ZoneId.systemDefault()).toEpochSecond();
            /*
             * 사용자 아이디
             * 이 아이디를 기준으로 서비스 사용자를 구분하며 최대 255바이트까지 설정할 수 있습니다
             */
            String userId ="sample_user_id";
            /*
             * 채팅에 노출할 사용자명
             * 금칙어에 해당하는 단어는 별표(*)로 대체되어 표시됩니다
             */
            String name = "my_nickname";
            /*
             * 접속자 통계에서 참조할 성별 정보입니다.
             * 남성(m), 여성(f), 기타(n, null, etc.)
             */
            String gender = "f";
            /*
            /* 접속자 통계에서 참조할 연령 정보입니다.
             * 임의의 숫자로 입력할 수 있으며 통계에는 5세 단위로 그룹화하여 표시합니다.
             */
            Integer age = 15;
            /*
             * 사용자 임의 데이터
             */
            String custom = "{Custom Data}";
            /*
             * 사용자 등급
             */
            int userScore = 34;
            /*
             * 사용자 유형
             */
            String userType = "VIP";
            /*
             * 사용자 프로필 이미지 URL
             */
            String profile = "https://image.shoplive.cloud/sample_profile.png";
    
            JwtBuilder builder = Jwts.builder()
                .signWith(SignatureAlgorithm.forName(algorithm), base64EncodedSecretKey)
                .setExpiration(new Date(expiration))
                .setIssuedAt(new Date())
                .claim("userId", userId)
                .claim("name", name)
                .claim("gender", gender)
                .claim("age", age)
                .claim("custom", custom)
                .claim("userScore", userScore)
                .claim("userType", userType)
                .claim("profile", profile);
          
            String jwt = builder.compact();
            System.out.printf("jwt: " + jwt);
        }
    }
    
    Result
    
    jwt: eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MTA1NzA1MDgsImlhdCI6MTYxMDUyNzMwOCwidXNlcklkIjoic2FtcGxlX3VzZXJfaWQiLCJuYW1lIjoibXlfbmlja25hbWUiLCJnZW5kZXIiOiJmIiwiYWdlIjoxNX0.0Z5YUo99149fIFyfqwxa-7SLyqC0RHR1T8P7jZLhpG8
    

    JWT를 생성하고 Java 이외의 프로그래밍 언어를 통해 인증을 실행하려면 SHOPLIVE 담당자에게 지원을 요청하세요.