在春季主要访问数据

时间:2018-01-02 08:37:27

标签: spring facebook spring-mvc facebook-graph-api spring-security

我的网络应用程序需要用户通过Facebook登录,然后Facebook将返回用户的信息,如:Facebook ID,用户名,电子邮件...

配置:

@SpringBootApplication
@EnableOAuth2Sso
@RestController
public class SocialApplication extends WebSecurityConfigurerAdapter {

    @RequestMapping("/user")
    public Principal user(Principal principal) {
        return principal;
    }

    public static void main(String[] args) {
        SpringApplication.run(SocialApplication.class, args);
    }

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

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**");
        web.ignoring().antMatchers("/static/**");
    }
}

WebController:

@Controller
public class WebController {
    @RequestMapping( value = {"/", "/index"})
    public String index(){
        return "index";
    }
}

JavaScript前端允许用户通过Facebook登录:

<body>
        <div class="container unauthenticated">
            With Facebook: <a href="/login">click here</a>
        </div>
        <div class="container authenticated" style="display:none">
            Logged in as: <span id="user"></span>
        </div>
        <div>
            <button id="btnLogout" onClick="logout()" class="btn btn-primary">Logout</button>
        </div>

        <script type="text/javascript">

            $("#btnLogout").hide();

            $.get("/user", function(data) {
                $("#user").html(data.userAuthentication.details.name);
                $(".unauthenticated").hide()
                $(".authenticated").show()
                $("#btnLogout").show();
            });

            var logout = function() {
                $.post("/logout", function() {
                    $("#user").html('');
                    $(".unauthenticated").show();
                    $(".authenticated").hide();
                    $("#btnLogout").hide();
                })

                return true;
            }
        </script>
    </body>

用户通过Facebook登录后,如果网络应用访问了网址:/user,则会返回retsult:

{
    "authorities": [
        {
            "authority": "ROLE_USER"
        }
    ],
    "details": {
        "remoteAddress": "0:0:0:0:0:0:0:1",
        "sessionId": "C7C446FC3169FFDDD68ADA8497F19CFC",
        "tokenValue": "EAASZB5Q8S4WYBAGHGhX0XzdGfRIAhm1fMZBScqNYcueCEIBcc3ZCQgfjrFsDRk1LioAFEk8XeXZAxFEKHGpE9LJ83hvNJcRZACzvCx2h14z2eCPAnLJ00soZCNw5276QZCJmD5Kg6xK7MrrIZAm5PKIj40fHIPVO33W25fZBrcBdg0ZCZBYo2gXhD2ZC",
        "tokenType": "bearer",
        "decodedDetails": null
    },
    "authenticated": true,
    "userAuthentication": {
        "authorities": [
            {
                "authority": "ROLE_USER"
            }
        ],
        "details": {
            "email": "deng.bunthai@yahoo.com",
            "name": "BunThai Deng",
            "id": "1676389552422181"
        },
        "authenticated": true,
        "principal": "1676389552422181",
        "credentials": "N/A",
        "name": "1676389552422181"
    },
    "principal": "1676389552422181",
    "clientOnly": false,
    "oauth2Request": {
        "clientId": "1335790916526438",
        "scope": [],
        "requestParameters": {},
        "resourceIds": [],
        "authorities": [],
        "approved": true,
        "refresh": false,
        "redirectUri": null,
        "responseTypes": [],
        "extensions": {},
        "refreshTokenRequest": null,
        "grantType": null
    },
    "credentials": "",
    "name": "1676389552422181"
}

问题是我如何访问主体或会话中的电子邮件?

1 个答案:

答案 0 :(得分:2)

我刚刚找到了这个问题的解决方案:

@RequestMapping("/user")
public Principal user(Principal principal) {

    Authentication a = SecurityContextHolder.getContext().getAuthentication();
    HashMap data = (HashMap) ((OAuth2Authentication) a).getUserAuthentication().getDetails();
    System.out.println(data.get("email"));

    return principal;
}