Saturday, May 9, 2020

透過 OAuth2.0 使用 Facebook 登入 範例

去 facebook develop 開發
新增 facebook login

pom.xml

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>2.1.3</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>webjars-locator-core</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security.oauth.boot</groupId>
            <artifactId>spring-security-oauth2-autoconfigure</artifactId>
            <version>2.1.5.RELEASE</version>
        </dependency>
    </dependencies>

appliceation.yml

security:
  oauth2:
    client:
      clientId: ===
      clientSecret: ====
      accessTokenUri: https://graph.facebook.com/oauth/access_token
      userAuthorizationUri: https://www.facebook.com/dialog/oauth
      tokenName: oauth_token
      authenticationScheme: query
      clientAuthenticationScheme: form
    resource:
      userInfoUri: https://graph.facebook.com/me

SpringBootFacebookLoginExampleApplication.java


@SpringBootApplication
@RestController
@EnableOAuth2Sso
public class SpringBootFacebookLoginExampleApplication {

 @GetMapping("/user")
    public Principal getUser(Principal user) {
     ObjectMapper mapper = new ObjectMapper();
     String user2;
  try {
   user2 = mapper.writeValueAsString(user);
      System.out.println(user2);
  } catch (JsonGenerationException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (JsonMappingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 
        return user;
    }
    public static void main(String[] args) {
        SpringApplication.run(SpringBootFacebookLoginExampleApplication.class, args);
    }

}

OAuth2Configuration.java


@EnableOAuth2Sso
@Configuration
public class OAuth2Configuration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .antMatcher("/**")
                .authorizeRequests()
                .antMatchers("/", "/login**", "/webjars/**", "/error**")
                .permitAll()
                .anyRequest()
                .authenticated();
    }

}

index.html

這邊要用ajex 應該也可
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <title>Demo</title>
    <meta name="description" content=""/>
    <meta name="viewport" content="width=device-width"/>
    <base href="/"/>
    <link rel="stylesheet" type="text/css" href="/webjars/bootstrap/css/bootstrap.min.css"/>
    <script type="text/javascript" src="/webjars/jquery/jquery.min.js"></script>
    <script type="text/javascript" src="/webjars/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<h1>Demo</h1>

<div class="container unauthenticated">
    Login With Facebook: <a href="/login">click here</a>
</div>
<div class="container authenticated" style="display:none">
    Logged into Facebook as: <span id="user"></span>
</div>
</div>
<script type="text/javascript">
    $.get("/user", function(data) {
        $("#user").html(data.userAuthentication.details.name);
        $(".unauthenticated").hide()
        $(".authenticated").show()
    });

</script>
</body>
</html>