invalidauthenticationtoken即使在刷新令牌之后也是如此

4smxwvx5  于 2021-06-30  发布在  Java
关注(0)|答案(0)|浏览(227)

我已经用java编写了一个桌面应用程序,可以从microsoft outlook帐户检索信息。我能够登录并获得一个在指定的1小时内正常工作的访问令牌。我还可以在小时到期之前刷新该令牌,并且新的访问令牌也可以工作。但是如果我在最初的1小时后尝试刷新,新令牌将无法工作。我有个错误。
我的代码在下面

import java.net.MalformedURLException;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Consumer;

import com.microsoft.aad.msal4j.DeviceCode;
import com.microsoft.aad.msal4j.DeviceCodeFlowParameters;
import com.microsoft.aad.msal4j.IAccount;
import com.microsoft.aad.msal4j.IAuthenticationResult;
import com.microsoft.aad.msal4j.ITokenCacheAccessAspect;
import com.microsoft.aad.msal4j.PublicClientApplication;
import com.microsoft.aad.msal4j.SilentParameters;
import com.microsoft.aad.msal4j.RefreshTokenParameters;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Date;
import java.util.NoSuchElementException;
import java.util.concurrent.RejectedExecutionException;
import java.util.prefs.Preferences;

/**
 * Authentication
 */
public class Authentication {
    private Preferences prefs = Preferences.userRoot().node("TEST_APP");
    private PublicClientApplication app;
    private Set<String> scopeSet;
    private ExecutorService pool;
    private String applicationId;
    private String expires = "NO_EXPIRES_SAVED";  
    //ITokenCacheAccessAspect persistenceAspect;
    // Set authority to allow only organizational accounts
    // Device code flow only supports organizational accounts
    private final String authority = "https://login.microsoftonline.com/common/";
    private AuthenticationListener listener;

    public void initialize(String applicationId, String[] scopes, AuthenticationListener listener) {
        System.out.println("Initializing authentication");

        applicationId = applicationId;
        scopeSet = Set.of(scopes);
        pool = Executors.newFixedThreadPool(1);

        // Loads cache from file
        //String tokenFile = "./serialized_cache.json";
        //String dataToInitCache = readResource(tokenFile);
        //persistenceAspect = new TokenPersistence(dataToInitCache, tokenFile);

        try {
            app = PublicClientApplication.builder(applicationId)
                .authority(authority)
                .executorService(pool)
                .build();

        } catch (MalformedURLException e) {
            return;
        }

        this.listener = listener;
    }

    public Boolean getUserAccessToken(LoginDialog loginDialog) {
        Boolean success = false;

        System.out.println("getUserAccessToken: scopes is: " + scopeSet.toString());

        // Create consumer to receive the DeviceCode object
        // This method gets executed during the flow and provides
        // the URL the user logs into and the device code to enter
        Consumer<DeviceCode> deviceCodeConsumer = (DeviceCode deviceCode) -> {
            loginDialog.stillWaiting = false;
            loginDialog.setText(deviceCode.message());

        };

        // Request a token, passing the requested permission scopes
        IAuthenticationResult result = null;
        try {
            result = app.acquireToken(
                DeviceCodeFlowParameters
                    .builder(scopeSet, deviceCodeConsumer)
                    .build()
            ).exceptionally(ex -> {
                System.out.println("Unable to authenticate - " + ex.getMessage());
                return null;
            }).join();
        } catch (RejectedExecutionException e) {
            System.out.println("getUserAccessToken: error getting token: " + e.toString());
        }

        if (result != null) {
            expires = result.expiresOnDate().toString();
            listener.saveToken(result);
            success = true;
            return success;
        }

        return success;
    }

    public boolean tokenStillValid() {
        Date expiration = new Date(expires);   
        System.out.println("tokenStillValid: expiration is: " + expiration);
        Date today = new Date();
        System.out.println("tokenStillValid: today is: " + today);

        if (expiration.after(today)){
            System.out.println("tokenStillValid: token is still valid");
        } else {
            System.out.println("tokenStillValid: token is expired");
        }

        return expiration.after(today);
    }

    public void refreshToken() {        
        try {
            Set<IAccount> accounts =  app.getAccounts().join();
            System.out.println("Account username is: " + accounts.iterator().next().username());
            SilentParameters parameters = SilentParameters.builder(scopeSet, accounts.iterator().next()).build();
            IAuthenticationResult result = (IAuthenticationResult) app.acquireTokenSilently(parameters).join();
            expires = result.expiresOnDate().toString();
            listener.saveToken(result);
        } catch (MalformedURLException | NoSuchElementException e){
            System.out.println("Error getting refresh token: " + e.toString() + " " + e.getLocalizedMessage());
            return;
        }

    }
}```

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题