【问题标题】:Accessing data in principal in spring [duplicate]在春季主要访问数据[重复]
【发布时间】:2018-06-11 23:24:54
【问题描述】:

我的网络应用程序需要用户通过 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/**");
    }
}

网络控制器:

@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登录后,如果web应用访问url:/user,会返回result:

{
    "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"
}

问题是如何在主体或会话中访问以获取电子邮件??

【问题讨论】:

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


    【解决方案1】:

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

    @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;
    }
    

    【讨论】:

    • 我遇到了同样的问题。即使将主体转换为 OAuth2Authentication 对我来说也是空的。身份验证成功后是否需要创建自定义主体??
    • 如果会话是由 OAuth 创建的,您可以通过 OAuth2Authentication 强制转换会话。例如,用户通过 Facebook 登录,Facebook 使用 OAuth2 保护第三方应用程序访问用户数据。之后,用户允许第三方应用,然后 OAuth2 为应用创建会话,我们可以通过 OAuth2Authentication 投射会话。此外,您无需执行“成功验证后创建自定义主体”这样的操作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2016-01-30
    • 2014-01-01
    • 2015-10-06
    • 1970-01-01
    • 2020-02-04
    • 1970-01-01
    相关资源
    最近更新 更多