大家好,我正在尝试实现 oauth 2.0 以通过 scribe 获取 facebook 访问 token 并不断收到空指针异常。下面的行不断出现空指针异常:
字符串authorizationUrl = oAuthService.getAuthorizaionUrl(Token.Empty())+"&"+STATE+"="+state;
下面是我的完整代码
@Controller
public class HomeController {
private static final String STATE = "state";
private String client_id = "********";
private String app_secret = "********";
private String url = "http://localhost:8080";
private static final Token EMPTY_TOKEN = null;
private OAuthService oAuthService;
private FacebookClient obj; //passing the token to restfb object
public HomeController() {}
public HomeController(OAuthService oAuthService) {
oAuthService = buildOAuthService(client_id, app_secret);
}
private OAuthService buildOAuthService(String client_id, String app_secret){
return new ServiceBuilder()
.provider(FacebookApi.class)
.apiKey(client_id)
.apiSecret(app_secret)
.callback(url + "/auth/facebook/callback")
.build();
}
@RequestMapping(value ="/login", method=RequestMethod.GET)
public String HomePage()
{
//home page and has the link to redirect to /auth/facebook
return "login";
}
//start the OAuth2 authorization flow
@RequestMapping(value="/auth/facebook")
public RedirectView startAuthentication(HttpSession httpSession) throws OAuthException {
String state = UUID.randomUUID().toString();
httpSession.setAttribute(STATE, state);
//Below is where i'm having a null pointer exception
String authorizationUrl = oAuthService.getAuthorizationUrl(Token.empty())+"&"+STATE+"="+state;
return new RedirectView(authorizationUrl);
}
@RequestMapping(value="/auth/facebook/callback")
public RedirectView callback(@RequestParam("code")String code, @RequestParam(STATE)String state, HttpSession httpsession) throws IOException
{
String stateFromSession = (String)httpsession.getAttribute(STATE);
if(!state.equals(stateFromSession)) {
return new RedirectView("/login");
}
Token accessToken = getAccessToken(code);
obj = new DefaultFacebookClient(accessToken.toString(), Version.VERSION_2_2);
return new RedirectView("/loggedin");
}
private Token getAccessToken(String code) {
Verifier verify = new Verifier(code);
return oAuthService.getAccessToken(Token.empty(), verify);
}
}
最佳答案
您私有(private)创建的对象变量“oAuthService”为空。 由于我们不知道整个逻辑,我假设这就是问题所在:
private OAuthService oAuthService;
public HomeController() {}
public HomeController(OAuthService oAuthService) {
oAuthService = buildOAuthService(client_id, app_secret);
}
如果将最后一个构造函数更改为:
public HomeController(OAuthService oAuthService) {
this.oAuthService = buildOAuthService(client_id, app_secret);
}
或
public HomeController(OAuthService oAuthService) {
this.oAuthService = oAuthService;
}
它会起作用。
编辑: 关于使用“this”的好帖子可以在这里找到:http://javapapers.com/core-java/explain-the-java-this-keyword/
关于java - 使用 scribe oauth facebook 的空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29962486/