com.linecorp.linesdk.LineAccessToken Java Examples

The following examples show how to use com.linecorp.linesdk.LineAccessToken. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PostLoginActivity.java    From line-sdk-starter-android-v2 with MIT License 6 votes vote down vote up
protected void onPostExecute(LineApiResponse<LineAccessToken> response) {

            if (response.isSuccess()) {
                String updatedAccessToken = lineApiClient.getCurrentAccessToken().getResponseData().getAccessToken();

                // Update the view
                TextView accessTokenField = (TextView) findViewById(R.id.accessTokenField);
                accessTokenField.setText(updatedAccessToken);
                Toast.makeText(getApplicationContext(), "Access Token has been refreshed.", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getApplicationContext(), "Could not refresh the access token.", Toast.LENGTH_SHORT).show();
                Log.e(TAG, response.getErrorData().toString());
            }

            unlockScreenOrientation();
        }
 
Example #2
Source File: LineApiClientImpl.java    From line-sdk-android with Apache License 2.0 6 votes vote down vote up
@Override
@NonNull
public LineApiResponse<LineAccessToken> getCurrentAccessToken() {
    InternalAccessToken internalAccessToken;
    try {
        internalAccessToken = accessTokenCache.getAccessToken();
    } catch (Exception exception) {
        return LineApiResponse.createAsError(
                LineApiResponseCode.INTERNAL_ERROR,
                new LineApiError("get access token fail:" + exception.getMessage())
        );
    }

    if (internalAccessToken == null) {
        return LineApiResponse.createAsError(
                LineApiResponseCode.INTERNAL_ERROR,
                new LineApiError("The cached access token does not exist."));
    }

    return LineApiResponse.createAsSuccess(new LineAccessToken(
            internalAccessToken.getAccessToken(),
            internalAccessToken.getExpiresInMillis(),
            internalAccessToken.getIssuedClientTimeMillis()));
}
 
Example #3
Source File: LineApiClientImplTest.java    From line-sdk-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetCurrentAccessToken() {
    LineApiResponse<LineAccessToken> response;
    LineAccessToken actualAccessToken;

    // the cached access token is null.
    response = target.getCurrentAccessToken();
    assertFalse(response.isSuccess());

    // the cached access token is not null.
    accessTokenCache.saveAccessToken(ACCESS_TOKEN);
    response = target.getCurrentAccessToken();

    assertTrue(response.isSuccess());
    actualAccessToken = response.getResponseData();
    assertNotNull(actualAccessToken);
    assertEquals(ACCESS_TOKEN.getAccessToken(), actualAccessToken.getTokenString());
    assertEquals(ACCESS_TOKEN.getExpiresInMillis(),
                 actualAccessToken.getExpiresInMillis());
    assertEquals(ACCESS_TOKEN.getIssuedClientTimeMillis(),
                 actualAccessToken.getIssuedClientTimeMillis());
}
 
Example #4
Source File: LineApiClientImplTest.java    From line-sdk-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testRefreshToken() {
    accessTokenCache.saveAccessToken(ACCESS_TOKEN);
    LineApiResponse<RefreshTokenResult> refreshTokenResponse =
            LineApiResponse.createAsSuccess(new RefreshTokenResult(
                    "newAccessToken", 999L, "newRefreshToken", Collections.emptyList()));
    doReturn(refreshTokenResponse)
            .when(internalOauthApiClient)
            .refreshToken(anyString(), any(InternalAccessToken.class));

    LineApiResponse<LineAccessToken> actualResponse = target.refreshAccessToken();

    verify(internalOauthApiClient, times(1)).refreshToken(CHANNEL_ID, ACCESS_TOKEN);
    assertTrue(actualResponse.isSuccess());
    assertNotNull(actualResponse.getResponseData());
    assertEquals("newAccessToken", actualResponse.getResponseData().getTokenString());
    assertEquals(999L, actualResponse.getResponseData().getExpiresInMillis());
    InternalAccessToken newAccessToken =
            accessTokenCache.getAccessToken();
    assertNotNull(newAccessToken);
    assertEquals("newAccessToken", newAccessToken.getAccessToken());
    assertEquals(999L, newAccessToken.getExpiresInMillis());
    assertTrue(newAccessToken.getIssuedClientTimeMillis() > 0);
    assertEquals("newRefreshToken", newAccessToken.getRefreshToken());
}
 
Example #5
Source File: LineApiClientImplTest.java    From line-sdk-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testRefreshTokenWithNoRefreshToken() {
    accessTokenCache.saveAccessToken(ACCESS_TOKEN);
    LineApiResponse<RefreshTokenResult> refreshTokenResponse =
            LineApiResponse.createAsSuccess(new RefreshTokenResult(
                    "newAccessToken", 999L, null, Collections.emptyList()));
    doReturn(refreshTokenResponse)
            .when(internalOauthApiClient)
            .refreshToken(anyString(), any(InternalAccessToken.class));

    LineApiResponse<LineAccessToken> actualResponse = target.refreshAccessToken();

    verify(internalOauthApiClient, times(1)).refreshToken(CHANNEL_ID, ACCESS_TOKEN);
    assertTrue(actualResponse.isSuccess());
    assertNotNull(actualResponse.getResponseData());
    assertEquals("newAccessToken", actualResponse.getResponseData().getTokenString());
    assertEquals(999L, actualResponse.getResponseData().getExpiresInMillis());
    assertTrue(actualResponse.getResponseData().getIssuedClientTimeMillis() > 0);
    InternalAccessToken newAccessToken =
            accessTokenCache.getAccessToken();
    assertNotNull(newAccessToken);
    assertEquals("newAccessToken", newAccessToken.getAccessToken());
    assertEquals(999L, newAccessToken.getExpiresInMillis());
    assertTrue(newAccessToken.getIssuedClientTimeMillis() > 0);
    assertEquals(ACCESS_TOKEN.getRefreshToken(), newAccessToken.getRefreshToken());
}
 
Example #6
Source File: LineApiClientImplTest.java    From line-sdk-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testRefreshTokenWithApiError() {
    accessTokenCache.saveAccessToken(ACCESS_TOKEN);
    LineApiResponse<RefreshTokenResult> refreshTokenResponse =
            LineApiResponse.createAsError(
                    LineApiResponseCode.INTERNAL_ERROR, LineApiError.DEFAULT);
    doReturn(refreshTokenResponse)
            .when(internalOauthApiClient)
            .refreshToken(anyString(), any(InternalAccessToken.class));

    LineApiResponse<LineAccessToken> actualResponse = target.refreshAccessToken();

    verify(internalOauthApiClient, times(1)).refreshToken(CHANNEL_ID, ACCESS_TOKEN);
    assertFalse(actualResponse.isSuccess());
    assertEquals(ACCESS_TOKEN, accessTokenCache.getAccessToken());
}
 
Example #7
Source File: InternalApisFragment.java    From line-sdk-android with Apache License 2.0 6 votes vote down vote up
@OnClick(R.id.revoke_access_token_btn)
void revokeToken() {
    startApiAsyncTask("revokeAccessToken", () -> {
        LineApiResponse<LineAccessToken> currentAccessTokenResponse = lineApiClient.getCurrentAccessToken();
        if (!currentAccessTokenResponse.isSuccess()) {
            return currentAccessTokenResponse;
        }
        try {
            String accessToken = currentAccessTokenResponse.getResponseData().getTokenString();
            String response = internalOauthApiClient.revokeAccessToken(channelId, accessToken);
            return LineApiResponse.createAsSuccess(response);
        } catch (IOException e) {
            return LineApiResponse.createAsError(
                    LineApiResponseCode.SERVER_ERROR,
                    new LineApiError(e));
        }
    });
}
 
Example #8
Source File: LineApiClientImplTest.java    From line-sdk-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testVerifyToken() {
    LineApiResponse<AccessTokenVerificationResult> expectedResponse =
            LineApiResponse.createAsSuccess(new AccessTokenVerificationResult(
                    "1234", 3L, Arrays.asList(Scope.FRIEND, Scope.GROUP)));
    doReturn(expectedResponse)
            .when(internalOauthApiClient)
            .verifyAccessToken(any(InternalAccessToken.class));
    accessTokenCache.saveAccessToken(ACCESS_TOKEN);

    LineApiResponse<LineCredential> actualResponse = target.verifyToken();

    assertTrue(actualResponse.isSuccess());
    verify(internalOauthApiClient, times(1)).verifyAccessToken(ACCESS_TOKEN);

    LineAccessToken verifiedAccessToken = actualResponse.getResponseData().getAccessToken();
    assertEquals(ACCESS_TOKEN.getAccessToken(), verifiedAccessToken.getTokenString());
    assertEquals(3L, verifiedAccessToken.getExpiresInMillis());
    assertTrue(ACCESS_TOKEN.getIssuedClientTimeMillis()
               != verifiedAccessToken.getIssuedClientTimeMillis());
    assertEquals(3L, verifiedAccessToken.getExpiresInMillis());
    assertEquals(Arrays.asList(Scope.FRIEND, Scope.GROUP),
                 actualResponse.getResponseData().getScopes());

    InternalAccessToken newAccessToken = accessTokenCache.getAccessToken();
    assertEquals(ACCESS_TOKEN.getAccessToken(), newAccessToken.getAccessToken());
    assertEquals(3L, newAccessToken.getExpiresInMillis());
    assertTrue(newAccessToken.getIssuedClientTimeMillis()
               != ACCESS_TOKEN.getIssuedClientTimeMillis());
    assertEquals(ACCESS_TOKEN.getRefreshToken(), newAccessToken.getRefreshToken());
}
 
Example #9
Source File: LineLogin.java    From cordova-line-login-plugin with Apache License 2.0 5 votes vote down vote up
private void refreshAccessToken(CallbackContext callbackContext) {
    try {
        lineApiClient.refreshAccessToken();
        LineAccessToken lineAccessToken = lineApiClient.getCurrentAccessToken().getResponseData();
        callbackContext.success(lineAccessToken.getTokenString());
    } catch (Exception e) {
        this.UnknownError(e.toString());
    }
}
 
Example #10
Source File: LineLogin.java    From cordova-line-login-plugin with Apache License 2.0 5 votes vote down vote up
private void getAccessToken(CallbackContext callbackContext) {
    try {
        JSONObject json = new JSONObject();
        LineAccessToken lineAccessToken = lineApiClient.getCurrentAccessToken().getResponseData();
        json.put("accessToken", lineAccessToken.getTokenString());
        json.put("expireTime", lineAccessToken.getEstimatedExpirationTimeMillis());
        callbackContext.success(json);
    } catch (Exception e) {
        this.UnknownError(e.toString());
    }
}
 
Example #11
Source File: LineApiClientImpl.java    From line-sdk-android with Apache License 2.0 5 votes vote down vote up
@NonNull
private LineApiResponse<LineCredential> verifyToken(@NonNull InternalAccessToken accessToken) {
    LineApiResponse<AccessTokenVerificationResult> response =
            oauthApiClient.verifyAccessToken(accessToken);
    if (!response.isSuccess()) {
        return LineApiResponse.createAsError(
                response.getResponseCode(), response.getErrorData());
    }
    AccessTokenVerificationResult verificationResult = response.getResponseData();
    long verifiedClientTimeMillis = System.currentTimeMillis();

    try {
        accessTokenCache.saveAccessToken(
                new InternalAccessToken(
                        accessToken.getAccessToken(),
                        verificationResult.getExpiresInMillis(),
                        verifiedClientTimeMillis,
                        accessToken.getRefreshToken()));
    } catch(Exception exception) {
        return LineApiResponse.createAsError(
                LineApiResponseCode.INTERNAL_ERROR,
                new LineApiError("save access token fail:" + exception.getMessage())
        );
    }

    return LineApiResponse.createAsSuccess(
            new LineCredential(
                    new LineAccessToken(
                            accessToken.getAccessToken(),
                            verificationResult.getExpiresInMillis(),
                            verifiedClientTimeMillis),
                    verificationResult.getScopes()));
}
 
Example #12
Source File: LineAuthenticationController.java    From line-sdk-android with Apache License 2.0 4 votes vote down vote up
@Override
protected LineLoginResult doInBackground(@Nullable BrowserAuthenticationApi.Result... params) {
    BrowserAuthenticationApi.Result authResult = params[0];
    String requestToken = authResult.getRequestToken();
    PKCECode pkceCode = authenticationStatus.getPKCECode();
    String sentRedirectUri = authenticationStatus.getSentRedirectUri();
    if (TextUtils.isEmpty(requestToken)
            || pkceCode == null
            || TextUtils.isEmpty(sentRedirectUri)) {
        return LineLoginResult.internalError("Requested data is missing.");
    }

    // Acquire access token
    LineApiResponse<IssueAccessTokenResult> accessTokenResponse =
            authApiClient.issueAccessToken(
                    config.getChannelId(), requestToken, pkceCode, sentRedirectUri);
    if (!accessTokenResponse.isSuccess()) {
        return LineLoginResult.error(accessTokenResponse);
    }

    IssueAccessTokenResult issueAccessTokenResult = accessTokenResponse.getResponseData();
    InternalAccessToken accessToken = issueAccessTokenResult.getAccessToken();
    List<Scope> scopes = issueAccessTokenResult.getScopes();

    LineProfile lineProfile = null;
    String userId = null;
    if (scopes.contains(Scope.PROFILE)) {
        // Acquire account information
        LineApiResponse<LineProfile> profileResponse = talkApiClient.getProfile(accessToken);
        if (!profileResponse.isSuccess()) {
            return LineLoginResult.error(profileResponse);
        }
        lineProfile = profileResponse.getResponseData();
        userId = lineProfile.getUserId();
    }

    // Cache the acquired access token
    accessTokenCache.saveAccessToken(accessToken);

    final LineIdToken idToken = issueAccessTokenResult.getIdToken();
    if (idToken != null) {
        try {
            validateIdToken(idToken, userId);
        } catch (final Exception e) {
            return LineLoginResult.internalError(e.getMessage());
        }
    }

    return new LineLoginResult.Builder()
            .nonce(authenticationStatus.getOpenIdNonce())
            .lineProfile(lineProfile)
            .lineIdToken(idToken)
            .friendshipStatusChanged(authResult.getFriendshipStatusChanged())
            .lineCredential(new LineCredential(
                    new LineAccessToken(
                            accessToken.getAccessToken(),
                            accessToken.getExpiresInMillis(),
                            accessToken.getIssuedClientTimeMillis()),
                    scopes
            ))
            .build();
}
 
Example #13
Source File: LineLoginResultTest.java    From line-sdk-android with Apache License 2.0 4 votes vote down vote up
@NonNull
private static LineCredential createLineCredential() {
    return new LineCredential(
            new LineAccessToken("accessToken", 1000, 2000),
            Arrays.asList(Scope.FRIEND, Scope.GROUP));
}
 
Example #14
Source File: LineLoginResultTest.java    From line-sdk-android with Apache License 2.0 4 votes vote down vote up
@Test
public void testEquals() {
    final LineLoginResult expected = loginResultBuilder().build();

    // equals
    assertEquals(expected, loginResultBuilder().build());

    // not equals: responseCode
    assertNotEquals(expected, loginResultBuilder()
            .responseCode(LineApiResponseCode.CANCEL)
            .build());

    // not equals: nonce
    assertNotEquals(expected, loginResultBuilder()
            .nonce(null)
            .build());

    assertNotEquals(expected, loginResultBuilder()
            .nonce("differentNonce")
            .build());

    // not equals: lineProfile
    assertNotEquals(expected, loginResultBuilder()
            .lineProfile(null)
            .build());

    assertNotEquals(expected, loginResultBuilder()
            .lineProfile(
                    new LineProfile("id2", "displayName", Uri.parse("http://line.me"),
                                    "statusMessage")
            )
            .build());

    // not equals: lineIdToken
    assertNotEquals(expected, loginResultBuilder()
            .lineIdToken(null)
            .build());

    assertNotEquals(expected, loginResultBuilder()
            .lineIdToken(
                    new Builder()
                            .issuer("https://access.line.me")
                            .subject("abcdef")
                            .audience("123456")
                            .issuedAt(now)
                            .expiresAt(oneHourLater)
                            .nonce("qwerty")
                            .name("displayName")
                            .picture("http://line.me")
                            .email("[email protected]")
                            .build()
            )
            .build());

    // not equals: friendshipStatusChanged
    assertNotEquals(expected, loginResultBuilder()
            .friendshipStatusChanged(null)
            .build());

    assertNotEquals(expected, loginResultBuilder()
            .friendshipStatusChanged(false)
            .build());

    // not equals: friendshipStatusChanged
    assertNotEquals(expected, loginResultBuilder()
            .lineCredential(null)
            .build());

    assertNotEquals(expected, loginResultBuilder()
            .lineCredential(
                    new LineCredential(
                            new LineAccessToken("accessToken-xxx", 1000, 2000),
                            Arrays.asList(Scope.FRIEND, Scope.GROUP, Scope.OPENID_CONNECT,
                                          Scope.OC_EMAIL))
            )
            .build());

    // not equals: errorData
    assertNotEquals(expected, loginResultBuilder()
            .errorData(null)
            .build());

    assertNotEquals(expected, loginResultBuilder()
            .errorData(new LineApiError("testErrorMessage2"))
            .build());
}
 
Example #15
Source File: LineAuthenticationControllerTest.java    From line-sdk-android with Apache License 2.0 4 votes vote down vote up
@Test
public void testSuccess() throws Exception {
    Intent newIntentData = new Intent();
    doReturn(BrowserAuthenticationApi.Result.createAsSuccess(REQUEST_TOKEN_STR, null))
            .when(browserAuthenticationApi)
            .getAuthenticationResultFrom(newIntentData);
    doReturn(LineApiResponse.createAsSuccess(ISSUE_ACCESS_TOKEN_RESULT))
            .when(authApiClient)
            .issueAccessToken(CHANNEL_ID, REQUEST_TOKEN_STR, PKCE_CODE, REDIRECT_URI);
    doReturn(LineApiResponse.createAsSuccess(ACCOUNT_INFO))
            .when(talkApiClient)
            .getProfile(ACCESS_TOKEN);
    doReturn(LineApiResponse.createAsSuccess(OPEN_ID_DISCOVERY_DOCUMENT))
            .when(authApiClient)
            .getOpenIdDiscoveryDocument();

    target.startLineAuthentication();

    Robolectric.getBackgroundThreadScheduler().runOneTask();
    Robolectric.getForegroundThreadScheduler().runOneTask();

    verify(browserAuthenticationApi, times(1))
            .getRequest(activity, config, PKCE_CODE, LINE_AUTH_PARAMS);

    target.onActivityResult(3 /* requestCode */, 0 /* resultCode */, null /* data */);
    target.handleIntentFromLineApp(newIntentData);

    Robolectric.getBackgroundThreadScheduler().runOneTask();
    Robolectric.getForegroundThreadScheduler().runOneTask();

    verify(activity, times(1)).onAuthenticationFinished(
            new LineLoginResult.Builder()
                    .responseCode(LineApiResponseCode.SUCCESS)
                    .nonce(NONCE)
                    .lineProfile(new LineProfile(USER_ID, DISPLAY_NAME, PICTURE_URL, STATUS_MESSAGE))
                    .lineIdToken(ID_TOKEN)
                    .friendshipStatusChanged(null)
                    .lineCredential(new LineCredential(
                            new LineAccessToken(ACCESS_TOKEN_STR, EXPIRES_IN, ISSUED_CLIENT_TIME),
                            SCOPE_LIST))
                    .errorData(LineApiError.DEFAULT)
                    .build()
    );

    assertEquals(ACCESS_TOKEN, accessTokenCache.getAccessToken());
}
 
Example #16
Source File: LineApiClient.java    From line-sdk-android with Apache License 2.0 2 votes vote down vote up
/**
 * Gets the access token that the SDK is using for the user.
 *
 * @return A {@link LineApiResponse} object. If the API call is successful,
 * a {@link LineApiResponse} object contains the {@link LineAccessToken} object that contains
 * the access token. If the API call fails, the payload of the {@link LineApiResponse} object is
 * <code>null</code>.
 */
@NonNull
LineApiResponse<LineAccessToken> getCurrentAccessToken();
 
Example #17
Source File: PostLoginActivity.java    From line-sdk-starter-android-v2 with MIT License 2 votes vote down vote up
protected LineApiResponse<LineAccessToken> doInBackground(Void... params) {

            return lineApiClient.refreshAccessToken();
        }
 
Example #18
Source File: LineApiClient.java    From line-sdk-android with Apache License 2.0 2 votes vote down vote up
/**
 * Refreshes the access token that the SDK is using for the user.
 *
 * @return A {@link LineApiResponse} object. If the API call is successful, the
 * {@link LineApiResponse} object contains a {@link LineAccessToken} object that contains
 * a new access token. If the API call fails, the payload of the {@link LineApiResponse}
 * object is <code>null</code>.
 */
@NonNull
LineApiResponse<LineAccessToken> refreshAccessToken();