401错误未知授权正在检索Google日历

如何解决401错误未知授权正在检索Google日历

| 当我执行CalendarService.setOAuthCredentials(oauthParameters,new OAuthHmacSha1Signer());我收到OAuthException 401错误未知授权标头。 我正在使用GWT + GAE,但我不知道为什么收到此错误,oauthParameters似乎还可以。 我得到用户登录 loginService.login 我检查我是否有 身份验证已经开启 oauthService.checkOauthTokenSecret 如果没有,我将重定向到Google GCalendar的认证页面 允许 我得到查询字符串 由Google返回,我获得了访问权限 令牌和访问令牌的秘密和 将其设置为用户实体以备后用 在oauthService.upgradeLogin上使用。 并尝试获取日历 oauthService.getPublicCalendars。 我正在将MVP模式与mvp4g框架一起使用,对不起,如果有点混乱0 :-) 知道为什么我会收到401错误吗?我认为这是关于我正在客户端和服务器以及外部页面上下移动的问题……并且缺少某些内容:-(但是所有参数似乎都已正确填充。 客户端
public void onStart(){
    GWT.log(\"onStart\");
    loginService.login(GWT.getHostPageBaseURL(),new AsyncCallback<LoginInfo>() {
        @Override
        public void onSuccess(LoginInfo result) {
            Common.loginInfo = result;
            if(Common.loginInfo.isLoggedIn()) { 
                oauthService.checkOauthTokenSecret(new AsyncCallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        if (result == null){
                            eventBus.OauthLogin();
                        }else{
                            oauthService.upgradeLogin(Window.Location.getQueryString(),Common.loginInfo,new AsyncCallback<LoginInfo>() {
                                @Override
                                public void onSuccess(LoginInfo result) {
                                    Common.loginInfo = result;
                                    getCitas();
                                }
                                @Override public void onFailure(Throwable caught) {
                                    Common.handleError(caught);                         
                                }
                            });
                        }
                    }
                    @Override public void onFailure(Throwable caught) {
                        Common.handleError(caught);                         
                    }
                });
            }else{
                eventBus.LoadLogin();
            }
        }
        @Override public void onFailure(Throwable caught) {
            Common.handleError(caught);
        }
    });
}
服务器端
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletContext;

import com.google.gdata.client.authn.oauth.GoogleOAuthHelper;
import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthException;
import com.google.gdata.client.authn.oauth.OAuthHmacSha1Signer;
import com.google.gdata.client.authn.oauth.OAuthParameters;
import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.data.calendar.CalendarEntry;
import com.google.gdata.data.calendar.CalendarFeed;
import com.google.gdata.util.ServiceException;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.rdt.citas.client.OAuthoritzationService;
import com.rdt.citas.client.shared.LoginInfo;

public class OAuthoritzationServiceImpl extends RemoteServiceServlet 
implements OAuthoritzationService {

/**
 * 
 */
private static final long serialVersionUID = 1L;

private static final Logger log = Logger.getLogger(OAuthoritzationServiceImpl.class.getName());

private static String KEY_PARAM = \"oauth_consumer_key\";
private static String SECRET_PARAM = \"oauth_consumer_secret\";
private static String SCOPE_PARAM = \"scope_calendars\";
private static String CALLBACK_PARAM = \"oauth_callback\";


public String checkOauthTokenSecret(){

    ServletContext context = this.getServletContext();
    getOauthParams(context);

    return (String) this.getThreadLocalRequest().getSession().getAttribute(\"oauthTokenSecret\");;
}

public String getApprovalOAuthPageURL() throws IOException{

    ServletContext context = this.getServletContext();
    getOauthParams(context);

    GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();

    oauthParameters.setOAuthConsumerKey(getFromSession(KEY_PARAM));
    oauthParameters.setOAuthConsumerSecret(getFromSession(SECRET_PARAM));
    oauthParameters.setScope(getFromSession(SCOPE_PARAM));
    oauthParameters.setOAuthCallback(getFromSession(CALLBACK_PARAM));
    GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(new OAuthHmacSha1Signer());

    try {                       
        oauthHelper.getUnauthorizedRequestToken(oauthParameters);

        String approvalPageUrl = oauthHelper.createUserAuthorizationUrl(oauthParameters);
        String oauthTokenSecret = oauthParameters.getOAuthTokenSecret();

        this.getThreadLocalRequest().getSession().setAttribute(\"oauthTokenSecret\",oauthTokenSecret);

        return approvalPageUrl;

    } catch (OAuthException e) {
        log.log(Level.WARNING,e.toString());
        return \"\";
    } finally{
    }

}

public LoginInfo upgradeLogin(String queryString,LoginInfo login){
    // receiving \'?key1=value1&key2=value2
    queryString = queryString.substring(1,queryString.length());
    String k = getFromSession(KEY_PARAM);
    String s = getFromSession(SECRET_PARAM);

    GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
    oauthParameters.setOAuthConsumerKey(k);
    oauthParameters.setOAuthConsumerSecret(s);

    String oauthTS = (String) this.getThreadLocalRequest().getSession().getAttribute(\"oauthTokenSecret\");//oauthParameters.getOAuthTokenSecret();
    oauthParameters.setOAuthTokenSecret(oauthTS);

    GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(new OAuthHmacSha1Signer());
    oauthHelper.getOAuthParametersFromCallback(queryString,oauthParameters);

    login.setQueryStringTokens(queryString);
    login.setAccessTokenSecret(oauthTS);

    try {
        String accesToken = oauthHelper.getAccessToken(oauthParameters);
        login.setTokenSecret(accesToken);
    } catch (OAuthException e) {
        log.log(Level.WARNING,e.toString());
    }
    return login;
} 

public ArrayList<String> getPublicCalendars(String accessToken,String accessTokenSecret){
    ArrayList<String> result = new ArrayList<String>();
    CalendarFeed calendarResultFeed = null;

    GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
    oauthParameters.setOAuthConsumerKey(getFromSession(KEY_PARAM));
    oauthParameters.setOAuthConsumerSecret(getFromSession(SECRET_PARAM));
    oauthParameters.setOAuthToken(accessToken);
    oauthParameters.setOAuthTokenSecret(accessTokenSecret);            
    oauthParameters.setOAuthType(OAuthParameters.OAuthType.THREE_LEGGED_OAUTH);
    oauthParameters.setScope(getFromSession(SCOPE_PARAM));

    CalendarService myService = new CalendarService(\"exampleCo-exampleApp-1\");                  

    try {
        myService.setOAuthCredentials(oauthParameters,new OAuthHmacSha1Signer());
        URL calendarFeedUrl = new URL(\"https://www.google.com/calendar/feeds/default/owncalendars/full\");
        calendarResultFeed = myService.getFeed(calendarFeedUrl,CalendarFeed.class);
    } catch (OAuthException e) {
        log.info(\"OAuthException\");
        log.log(Level.WARNING,e.toString());
        e.printStackTrace();
    } catch (MalformedURLException e) {
        log.info(\"MalformedURLException\");
        log.log(Level.WARNING,e.toString());
        e.printStackTrace();
    } catch (IOException e) {
        log.info(\"IOException\");
        log.log(Level.WARNING,e.toString());
        e.printStackTrace();
    } catch (ServiceException e) {
        log.info(\"ServiceException\");
        log.log(Level.WARNING,e.toString());
        e.printStackTrace();
    }

    if (calendarResultFeed != null && calendarResultFeed.getEntries() != null) {
        for (int i = 0; i < calendarResultFeed.getEntries().size(); i++) {
            CalendarEntry entry = calendarResultFeed.getEntries().get(i);
            result.add(entry.getTitle().getPlainText());              
        } 
    }
    return result;
}


private void getOauthParams(ServletContext context) {
    this.getThreadLocalRequest().getSession()
        .setAttribute(KEY_PARAM,context.getInitParameter(KEY_PARAM));
    this.getThreadLocalRequest().getSession()
        .setAttribute(SECRET_PARAM,context.getInitParameter(SECRET_PARAM));
    this.getThreadLocalRequest().getSession()
        .setAttribute(SCOPE_PARAM,context.getInitParameter(SCOPE_PARAM));
    this.getThreadLocalRequest().getSession()
        .setAttribute(CALLBACK_PARAM,context.getInitParameter(CALLBACK_PARAM));
}

private String getFromSession(String param){
    return (String) this.getThreadLocalRequest().getSession().getAttribute(param);
}

}
    

解决方法

        我最近一直在使用oAuth。在upgradeLogin(...)内,当您升级到访问令牌时,不会获取相应的访问令牌密钥。 getAccessToken()请求之后的访问令牌密钥与请求之前的访问令牌密钥不同。您当前正在设置访问令牌密钥(通过login.setAccessTokenSecret(oauthTS)),它是您正在使用的预先更新的访问令牌密钥值。您需要将其设置为更新请求后返回的访问令牌秘密值:
String accesToken = oauthHelper.getAccessToken(oauthParameters);
String accesTokenSecret = oauthParameters.getOAuthTokenSecret();                
login.setTokenSecret(accesToken);
login.setAccessTokenSecret(accesTokenSecret);
您可能还希望将此更新的令牌/密钥对存储在某处。然后,应该在以下行的getPublicCalendars(...)内部使用此访问令牌密钥的值:
oauthParameters.setOAuthTokenSecret(accessTokenSecret);
更新后访问令牌/秘密对是长期存在的,因此可以重新使用(无需再次更新),直到被撤消为止。 偶然地,我发现oAuth Playground Tool对诊断我的问题很有用。 我希望这有帮助,     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-