如何延长 OAuth 2 存储凭据的有效期?

huangapple go评论77阅读模式
英文:

How to extend the duration of a Oauth 2 StoredCredential

问题

我正在为获取Google表格内容创建一个API,但是每小时,"StoredCredential"令牌会过期,所以我必须使用UI重新登录(选择Google账户的菜单),如何延长令牌的寿命,因为程序每天都会启动,我不想每天都输入我的Google账户?

我已经尝试更改过期时间,但没有成功。

以下是我的实际代码:

private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

private static final String TOKENS_DIRECTORY_PATH = "u:\\tokens";

private static final List<String> SCOPES =
    Arrays.asList(SheetsScopes.SPREADSHEETS, SheetsScopes.DRIVE);

private static final String CREDENTIALS_FILE_PATH = "credentials.json";

private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws Exception {
    // Load client secrets.
    InputStream in = new FileInputStream(CREDENTIALS_FILE_PATH);
    if (in == null) {
        throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
    }
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(TOKENS_DIRECTORY_PATH));
    DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore("StoredCredential");
    datastore.values().forEach(x -> x.setExpirationTimeMilliseconds((long) 999999999));
    //DEBUG
    datastore.values().forEach(x -> System.out.println(x.getExpirationTimeMilliseconds()));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
        HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
        //.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
        .setCredentialDataStore(datastore)
        .setAccessType("online")
        .setApprovalPrompt(null)
        .build();
    LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();

    return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
英文:

I'm making a API for taking the content of a google sheet but every hour, the token "StoredCredential" expire so I must log back with the UI (the menu where you choose your google account), how can I extend the lifespan of the token since the program will be launch everyday and I don't want to input my google account every days?
I already tried to change the expiration time but that didn't work

Here my actual code :

	private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
	
	private static final String TOKENS_DIRECTORY_PATH = &quot;u:\\tokens&quot;;

	private static final List&lt;String&gt; SCOPES =
	        Arrays.asList(SheetsScopes.SPREADSHEETS,SheetsScopes.DRIVE);

	private static final String CREDENTIALS_FILE_PATH = &quot;credentials.json&quot;;

    private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws Exception {
		// Load client secrets.
		InputStream in = new FileInputStream(CREDENTIALS_FILE_PATH);
		if (in == null) {
			throw new FileNotFoundException(&quot;Resource not found: &quot; + CREDENTIALS_FILE_PATH);
		}
		GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
		
		  FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(TOKENS_DIRECTORY_PATH));
			  DataStore&lt;StoredCredential&gt; datastore = fileDataStoreFactory.getDataStore(&quot;StoredCredential&quot;);
			  datastore.values().forEach(x -&gt; x.setExpirationTimeMilliseconds((long) 999999999));
              //DEBUG
			  datastore.values().forEach(x -&gt; System.out.println(x.getExpirationTimeMilliseconds()));
			  
		// Build flow and trigger user authorization request.
		GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
				HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
				//.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
				.setCredentialDataStore(datastore)
				.setAccessType(&quot;online&quot;)
				.setApprovalPrompt(null)
				.build();
		LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
		
		return new AuthorizationCodeInstalledApp(flow, receiver).authorize(&quot;user&quot;);
	}

答案1

得分: 0

在阅读了我的其他问题的文档后,我找到了一种方法来延长StoredCredential文件的生命周期,您需要将访问类型从在线更改为离线。

修正后的版本:

private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

private static final String TOKENS_DIRECTORY_PATH = "u:\\tokens";

private static final List<String> SCOPES =
        Arrays.asList(SheetsScopes.SPREADSHEETS, SheetsScopes.DRIVE);

private static final String CREDENTIALS_FILE_PATH = "credentials.json";

private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws Exception {
    // Load client secrets.
    InputStream in = new FileInputStream(CREDENTIALS_FILE_PATH);
    if (in == null) {
        throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
    }
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(TOKENS_DIRECTORY_PATH));
    DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore("StoredCredential");
    datastore.values().forEach(x -> x.setExpirationTimeMilliseconds((long) 999999999));
    //DEBUG
    datastore.values().forEach(x -> System.out.println(x.getExpirationTimeMilliseconds()));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            //.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
            .setCredentialDataStore(datastore)
            /* Here, we change the accessType */
            .setAccessType("offline")
            .setApprovalPrompt(null)
            .build();
    LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
英文:

After reading the documentation for my other question, i found a way to extend the lifespan of the StoredCredential file, you need to change the Access Type from online to offline.

Corrected version :

 private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    
    private static final String TOKENS_DIRECTORY_PATH = &quot;u:\\tokens&quot;;

    private static final List&lt;String&gt; SCOPES =
            Arrays.asList(SheetsScopes.SPREADSHEETS,SheetsScopes.DRIVE);

    private static final String CREDENTIALS_FILE_PATH = &quot;credentials.json&quot;;

    private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws Exception {
        // Load client secrets.
        InputStream in = new FileInputStream(CREDENTIALS_FILE_PATH);
        if (in == null) {
            throw new FileNotFoundException(&quot;Resource not found: &quot; + CREDENTIALS_FILE_PATH);
        }
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
        
          FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(TOKENS_DIRECTORY_PATH));
              DataStore&lt;StoredCredential&gt; datastore = fileDataStoreFactory.getDataStore(&quot;StoredCredential&quot;);
              datastore.values().forEach(x -&gt; x.setExpirationTimeMilliseconds((long) 999999999));
              //DEBUG
              datastore.values().forEach(x -&gt; System.out.println(x.getExpirationTimeMilliseconds()));
              
        // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
                //.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
                .setCredentialDataStore(datastore)
                /* Here, we change the accessType */
                .setAccessType(&quot;offline&quot;)
                .setApprovalPrompt(null)
                .build();
        LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();

huangapple
  • 本文由 发表于 2020年8月5日 21:21:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/63266138.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定