eunja511005 / AutoCoding

0 stars 0 forks source link

안드로이드 API 호출전 토큰 유효성 점검 샘플 #134

Open ywbestPark opened 1 year ago

ywbestPark commented 1 year ago
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final String API_URL = "https://your-api-url.com/resource";
    private static final String TOKEN = "your-jwt-token";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // API 호출을 위한 AsyncTask 실행
        new ApiCallTask().execute();
    }

    private class ApiCallTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... voids) {
            try {
                // 현재 시간 확인
                long currentTimeMillis = System.currentTimeMillis();

                // 토큰 유효성 검사
                if (isTokenValid(currentTimeMillis)) {
                    // 유효한 토큰으로 API 호출
                    URL url = new URL(API_URL);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setRequestProperty("Authorization", "Bearer " + TOKEN);

                    int responseCode = connection.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                        String inputLine;
                        StringBuilder response = new StringBuilder();

                        while ((inputLine = in.readLine()) != null) {
                            response.append(inputLine);
                        }
                        in.close();

                        return response.toString();
                    } else {
                        Log.e(TAG, "API request failed with response code: " + responseCode);
                    }
                } else {
                    Log.e(TAG, "Token is invalid. Refresh or reauthenticate.");
                }
            } catch (Exception e) {
                Log.e(TAG, "Error: " + e.getMessage());
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            if (result != null) {
                Log.d(TAG, "API Response: " + result);
                // API 응답을 처리하는 코드를 여기에 추가
            } else {
                Log.e(TAG, "API request failed or token is invalid.");
            }
        }
    }

    private boolean isTokenValid(long currentTimeMillis) {
        try {
            // 토큰의 만료 시간을 확인하고 현재 시간과 비교
            String[] tokenParts = TOKEN.split("\\.");
            String tokenPayload = tokenParts[1];
            byte[] payloadBytes = android.util.Base64.decode(tokenPayload, android.util.Base64.DEFAULT);
            String payloadJson = new String(payloadBytes);

            JSONObject payloadObject = new JSONObject(payloadJson);
            long expirationTimeMillis = payloadObject.getLong("exp") * 1000; // 토큰의 만료 시간 (초 단위)

            return expirationTimeMillis > currentTimeMillis;
        } catch (JSONException e) {
            Log.e(TAG, "Error parsing token payload: " + e.getMessage());
            return false;
        }
    }
}
ywbestPark commented 1 year ago
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 토큰 생성
        String token = JwtTokenManager.generateToken("user123");
        Log.d(TAG, "Generated Token: " + token);

        // 토큰 저장 (SharedPreferences 또는 다른 안전한 저장소를 사용하세요)
        TokenManager.saveToken(this, token);

        // 토큰 불러오기
        String savedToken = TokenManager.getToken(this);

        // 토큰 유효성 확인
        if (JwtTokenManager.isTokenValid(savedToken)) {
            Log.d(TAG, "Token is valid.");
            // API 호출 등의 작업 수행
        } else {
            Log.d(TAG, "Token is invalid. Refresh or reauthenticate.");
            // 토큰 갱신 또는 다시 로그인 수행
        }
    }
}
ywbestPark commented 1 year ago
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import java.security.Key;
import java.util.Date;

public class JwtTokenManager {

    private static final String SECRET_KEY = "your-secret-key"; // 실제로는 보안에 강한 키를 사용하세요
    private static final long EXPIRATION_TIME = 15 * 60 * 1000; // 토큰 만료 시간 (15분)

    public static String generateToken(String subject) {
        Date now = new Date();
        Date expirationDate = new Date(now.getTime() + EXPIRATION_TIME);

        Key secretKey = Keys.hmacShaKeyFor(SECRET_KEY.getBytes());

        String token = Jwts.builder()
                .setSubject(subject)
                .setIssuedAt(now)
                .setExpiration(expirationDate)
                .signWith(secretKey, SignatureAlgorithm.HS256)
                .compact();

        return token;
    }

    public static boolean isTokenValid(String token) {
        // 토큰 유효성 확인 로직
        try {
            Claims claims = Jwts.parserBuilder()
                    .setSigningKey(SECRET_KEY.getBytes())
                    .build()
                    .parseClaimsJws(token)
                    .getBody();

            Date expiration = claims.getExpiration();
            Date now = new Date();
            return !expiration.before(now);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
ywbestPark commented 1 year ago
import android.content.Context;
import android.content.SharedPreferences;

public class TokenManager {

    private static final String PREF_NAME = "token_prefs";
    private static final String TOKEN_KEY = "auth_token";

    public static void saveToken(Context context, String token) {
        SharedPreferences preferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(TOKEN_KEY, token);
        editor.apply();
    }

    public static String getToken(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        return preferences.getString(TOKEN_KEY, null);
    }
}