Last active
August 29, 2015 14:11
-
-
Save steppat/787d63e5e10ea53b0283 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Obs: http://tinyurl.com/oauth2-github | |
1) Acesse a sua conta no github e registre a aplicacao fj36-livraria, callback é: | |
http://localhost:8088/fj36-livraria/oauth/callback | |
------------------------------ | |
2) Baixe o JAR: | |
http://central.maven.org/maven2/org/scribe/scribe/1.3.5/scribe-1.3.5.jar | |
e coloque na pasta WEB-INF/lib da aplicação fj36-livraria. | |
------------------------------ | |
3) Crie o arquivo oauth-index.jsp dentro da pasta WebContent/WEB-INF/views/: | |
<%@ page language="java" contentType="text/html; charset=UTF-8" | |
pageEncoding="UTF-8"%> | |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> | |
<html> | |
<body> | |
Faremos uma requisição através deste link à uma action do nosso controller (OAuthController). Que irá chamar o GitHub, enviando o <i>Client_id</i> e os <i>escopos</i> (recursos que nossa aplicação irá acessar) | |
<br><br> | |
<a href="/fj36-livraria/oauth/login-github">Logar com github</a> | |
</body> | |
</html> | |
------------------------- | |
4) Crie a classe de configuração: | |
package br.com.caelum.oauth; | |
import org.scribe.builder.api.DefaultApi20; | |
import org.scribe.model.OAuthConfig; | |
//classe de configuracao | |
public class GithubApi extends DefaultApi20 { | |
@Override | |
public String getAccessTokenEndpoint() { | |
//É utilizado pelo método getAccessToken() da classe OAuthService | |
return "https://github.com/login/oauth/access_token"; | |
} | |
@Override | |
public String getAuthorizationUrl(OAuthConfig config) { | |
//URL do primeiro request para GitHub enviando Client_ID e scope (permissões) | |
//Client secret é opcional e Redirect URI está cadastrado no cadastro do GitHub | |
return String.format("https://github.com/login/oauth/authorize?scope=user:email&client_id=%s", config.getApiKey()); | |
} | |
} | |
----------------------------- | |
5) Crie a classe controlador: | |
package br.com.caelum.livraria.controller; | |
import javax.annotation.PostConstruct; | |
import org.scribe.builder.ServiceBuilder; | |
import org.scribe.model.OAuthRequest; | |
import org.scribe.model.Response; | |
import org.scribe.model.Token; | |
import org.scribe.model.Verb; | |
import org.scribe.model.Verifier; | |
import org.scribe.oauth.OAuthService; | |
import org.springframework.stereotype.Controller; | |
import org.springframework.ui.Model; | |
import org.springframework.web.bind.annotation.RequestMapping; | |
import org.springframework.web.bind.annotation.RequestParam; | |
import org.springframework.web.servlet.mvc.support.RedirectAttributes; | |
import br.com.caelum.oauth.GithubApi; | |
//Docu: https://github.com/fernandezpablo85/scribe-java | |
@Controller | |
@RequestMapping("/oauth") | |
public class OAuthController { | |
private final Token EMPTY_TOKEN = null; | |
private OAuthService service; | |
@PostConstruct | |
public void prepareOAuthService() { | |
this.service = new ServiceBuilder() | |
.provider(GithubApi.class) | |
.apiKey("seuClientIdAqui") | |
.apiSecret("seuClientSecretAqui") | |
.callback("http://localhost:8088/fj36-livraria/oauth/callback") | |
.build(); | |
} | |
@RequestMapping("/index") | |
public String oauthIndex() { | |
return "oauth-index"; | |
} | |
@RequestMapping("/login-github") | |
public String redirectToGithub() { | |
String authorizationUrl = service.getAuthorizationUrl(EMPTY_TOKEN); | |
return "redirect:" + authorizationUrl; | |
} | |
@RequestMapping("/callback") | |
public String callback(@RequestParam("code") String autenticationToken, Model model) { | |
Verifier verifier = new Verifier(autenticationToken); | |
//request para pegar o access token | |
Token accessToken = service.getAccessToken(EMPTY_TOKEN, verifier); | |
String token = accessToken.getToken(); | |
//System.out.println("RAW_RESPONSE: " + accessToken.getRawResponse()); | |
model.addAttribute("accessToken", token); | |
model.addAttribute("autenticationToken", autenticationToken); | |
return "oauth-logado"; | |
} | |
@RequestMapping("/githubRequest") | |
public String githubRequest(@RequestParam("accessToken") String token, RedirectAttributes redirectAttributes) { | |
token = token.trim(); | |
OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.github.com/user/emails"); | |
request.addBodyParameter("access_token", token); | |
service.signRequest(new Token(token, ""), request); | |
Response response = request.send(); | |
String body = response.getBody(); | |
redirectAttributes.addFlashAttribute("responseBody", body); | |
return "redirect:logado"; | |
} | |
@RequestMapping("/logado") | |
public String logado() { | |
return "oauth-logado"; | |
} | |
} | |
----------------------------- | |
6) Crie o arquivo oauth-logado.jsp dentro da pasta WebContent/WEB-INF/views/ | |
<%@ page language="java" contentType="text/html; charset=UTF-8" | |
pageEncoding="UTF-8"%> | |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> | |
<html> | |
<body> | |
Código de autenticaçao: ${autenticationToken}<br> | |
AccessToken (Authorization:Bearer): ${accessToken} | |
<br><br>Cole no campo abaixo o AccessToken para testar o request autorizado. | |
<br><br> | |
<form action="githubRequest"> | |
<label for="token">AccessToken:</label> | |
<input type="text" name="accessToken"> | |
<input type="submit" value="Enviar Request ao Github"> | |
</form> | |
<br><br> | |
${responseBody} | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment