即使刷新令牌后也无效验证令牌

时间:2020-09-07 00:06:52

标签: java graph microsoft-graph-api msal

我已经用Java编写了一个桌面应用程序,可以从Microsoft Outlook帐户中检索信息。我可以登录并获得一个在指定的1个小时内正常工作的访问令牌。我还可以在小时结束之前刷新该令牌,并且新的访问令牌也可以使用。但是,如果我尝试在最初的1小时后刷新,则新令牌将不起作用。我收到401未经授权的错误。

我的代码在下面


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;
        }

    }
}```

0 个答案:

没有答案
相关问题