Merge pull request #5314 from freddyaott/master

[BAEL-1519] Guide to ScribeJava
This commit is contained in:
José Carlos Valero Sánchez 2018-09-23 20:48:55 +01:00 committed by GitHub
commit 738d65b9be
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 422 additions and 2 deletions

View File

@ -8,12 +8,30 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<artifactId>parent-boot-1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-1</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>com.github.scribejava</groupId>
<artifactId>scribejava-apis</artifactId>
<version>${scribejava.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
@ -25,6 +43,9 @@
<properties>
<junit.version>4.12</junit.version>
<spring-boot-maven-plugin.version>2.0.4.RELEASE</spring-boot-maven-plugin.version>
<scribejava.version>5.6.0</scribejava.version>
</properties>
</project>

View File

@ -0,0 +1,15 @@
package com.baeldung.scribejava;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ScribejavaApplication {
public static void main(String[] args) {
SpringApplication.run(ScribejavaApplication.class, args);
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.scribejava.api;
import com.github.scribejava.core.builder.api.DefaultApi20;
public class MyApi extends DefaultApi20 {
private MyApi() {
}
private static class InstanceHolder {
private static final MyApi INSTANCE = new MyApi();
}
public static MyApi instance() {
return InstanceHolder.INSTANCE;
}
@Override
public String getAccessTokenEndpoint() {
return "http://localhost:8080/oauth/token";
}
@Override
protected String getAuthorizationBaseUrl() {
return null;
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.scribejava.controller;
import com.baeldung.scribejava.service.GoogleService;
import com.github.scribejava.core.model.OAuth2AccessToken;
import com.github.scribejava.core.model.OAuthRequest;
import com.github.scribejava.core.model.Response;
import com.github.scribejava.core.model.Verb;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
@RestController
public class GoogleController {
@Autowired
private GoogleService service;
@GetMapping(value ="/me/google")
public void me(HttpServletResponse response){
String auth = service.getService().getAuthorizationUrl();
response.setHeader("Location", auth);
response.setStatus(302);
}
@GetMapping(value = "/auth/google")
public String google(@RequestParam String code, HttpServletResponse servletResponse){
try {
OAuth2AccessToken token = service.getService().getAccessToken(code);
OAuthRequest request = new OAuthRequest(Verb.GET, "https://www.googleapis.com/oauth2/v1/userinfo?alt=json");
service.getService().signRequest(token, request);
Response response = service.getService().execute(request);
return response.getBody();
}catch (Exception e){
servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
}
return null;
}
}

View File

@ -0,0 +1,57 @@
package com.baeldung.scribejava.controller;
import com.baeldung.scribejava.service.TwitterService;
import com.github.scribejava.core.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
@RestController
public class TwitterController {
@Autowired
private TwitterService service;
@GetMapping(value ="/me/twitter")
public String me(HttpServletResponse servletResponse){
try {
OAuth1RequestToken requestToken = service.getService().getRequestToken();
String auth = service.getService().getAuthorizationUrl(requestToken);
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("rundll32 url.dll,FileProtocolHandler " + auth);
} catch (IOException e) {
servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return null;
}
System.out.println("Insert twitter code:");
Scanner in = new Scanner(System.in);
String oauthverifier = in.nextLine();
final OAuth1AccessToken accessToken = service.getService().getAccessToken(requestToken,oauthverifier);
OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.twitter.com/1.1/account/verify_credentials.json");
service.getService().signRequest(accessToken, request);
Response response = service.getService().execute(request);
return response.getBody();
} catch (IOException | InterruptedException | ExecutionException e) {
servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
}
return null;
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.scribejava.controller;
import com.baeldung.scribejava.service.MyService;
import com.github.scribejava.core.model.OAuth2AccessToken;
import com.github.scribejava.core.model.OAuthRequest;
import com.github.scribejava.core.model.Response;
import com.github.scribejava.core.model.Verb;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.security.Principal;
@RestController(value = "/user")
public class UserController {
@Autowired
private MyService service;
@GetMapping("/me/myapi")
public String me(@RequestParam String username, @RequestParam String password, HttpServletResponse responsehttp) {
try {
OAuth2AccessToken token = service.getService().getAccessTokenPasswordGrant(username, password);
OAuthRequest request = new OAuthRequest(Verb.GET, "http://localhost:8080/me");
service.getService().signRequest(token, request);
Response response = service.getService().execute(request);
return response.getBody();
} catch (Exception e) {
responsehttp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
}
return null;
}
@GetMapping("/me")
public Principal user(Principal principal) {
return principal;
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.scribejava.oauth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
@Configuration
@EnableAuthorizationServer
public class AuthServiceConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("baeldung_api_key")
.secret("baeldung_api_secret")
.authorizedGrantTypes("password","refresh_token")
.scopes("read","write").autoApprove(true);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.authenticationManager(authenticationManager)
.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
}
}

View File

@ -0,0 +1,53 @@
package com.baeldung.scribejava.oauth;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
@Configuration
@EnableResourceServer
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.headers().frameOptions().disable()
.and()
.csrf().disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("baeldung")
.password("scribejava")
.roles("USER");
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@EnableResourceServer
@Configuration
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/user/me").authenticated()
.and()
.csrf().disable();
}
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.scribejava.service;
import com.github.scribejava.apis.GoogleApi20;
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.oauth.OAuth20Service;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
public class GoogleService {
private OAuth20Service service;
private final String API_KEY = "api_key";
private final String API_SECRET = "api_secret";
private final String SCOPE = "https://www.googleapis.com/auth/userinfo.email";
private final String CALLBACK = "http://localhost:8080/auth/google";
@PostConstruct
private void init(){
this.service = new ServiceBuilder(API_KEY)
.apiSecret(API_SECRET)
.scope(SCOPE)
.callback(CALLBACK)
.build(GoogleApi20.instance());
}
public OAuth20Service getService() {
return service;
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.scribejava.service;
import com.baeldung.scribejava.api.MyApi;
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.oauth.OAuth20Service;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
public class MyService {
private OAuth20Service service;
private final String API_KEY = "baeldung_api_key";
private final String API_SECRET = "baeldung_api_secret";
@PostConstruct
private void init(){
this.service = new ServiceBuilder(API_KEY)
.apiSecret(API_SECRET)
.scope("read write")
.build(MyApi.instance());
}
public OAuth20Service getService() {
return service;
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.scribejava.service;
import com.github.scribejava.apis.TwitterApi;
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.oauth.OAuth10aService;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
public class TwitterService {
private final String API_KEY = "api_key";
private final String API_SECRET = "api_secret";
private OAuth10aService service;
@PostConstruct
private void init(){
this.service = new ServiceBuilder(API_KEY)
.apiSecret(API_SECRET)
.build(TwitterApi.instance());
}
public OAuth10aService getService(){
return service;
}
}

View File

@ -0,0 +1 @@
security.oauth2.resource.filter-order = 3

View File

@ -0,0 +1,17 @@
package com.baeldung.scribejava;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ScribejavaUnitTest {
@Test
public void contextLoad(){
}
}