Spring Security:如何从校长那里获取详细信息?

时间:2017-10-03 15:08:54

标签: java spring-security

使用spring boot和spring security,用户的详细信息在主体对象中可用。但它只有很少的方法来检索细节,例如getName()

如何从中获取其他详细信息?

目前我的班级看起来像这样

@SpringBootApplication
@RestController
public class DemoOAuth2Application {

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


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

它返回此,

{
  "authorities": [
    {
      "authority": "ROLE_USER"
    }
  ],
  "details": {
    "remoteAddress": "0:0:0:0:0:0:0:1",
    "sessionId": "43Fxxxxxx",
    "tokenValue": "ya29.xxxxxxxxx",
    "tokenType": "Bearer",
    "decodedDetails": null
  },
  "authenticated": true,
  "userAuthentication": {
    "authorities": [
      {
        "authority": "ROLE_USER"
      }
    ],
    "details": {
      "id": "106xxxxx",
      "email": "xxxxxxxx@gmail.com",
      "verified_email": true,
      "name": "xxxx yyyyyy",
      "given_name": "xxxxxx",
      "family_name": "yyyyy",
      "link": "https://plus.google.com/xxxxxxxxxx",
      "picture": "https://lh5.googleusercontent.com/xxxxxx/photo.jpg",
      "locale": "en"
    },
    "authenticated": true,
    "principal": "106xxxxx",
    "credentials": "N/A",
    "name": "106xxxxxxx"
  },
  "principal": "106xxxxxxxxxxx",
  "clientOnly": false,
  "credentials": "",
  "oauth2Request": {
    "clientId": "xxxxxxxxx.apps.googleusercontent.com",
    "scope": [],
    "requestParameters": {},
    "resourceIds": [],
    "authorities": [],
    "approved": true,
    "refresh": false,
    "redirectUri": null,
    "responseTypes": [],
    "extensions": {},
    "refreshTokenRequest": null,
    "grantType": null
  },
  "name": "106xxxxxxxxxx"
}

但是我不想返回所有数据,而是只返回我需要的特定数据。如何获取该数据(特别是电子邮件,名称,链接,图片)。

2 个答案:

答案 0 :(得分:4)

import org.springframework.security.oauth2.provider.OAuth2Authentication;

@SpringBootApplication
@RestController
public class DemoOAuth2Application {

    @RequestMapping("/user")
    public Authentication user(OAuth2Authentication authentication) {
        LinkedHashMap<String, Object> properties = (LinkedHashMap<String, Object>) authentication.getUserAuthentication().getDetails();
        return properties.get("email");
    }


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

答案 1 :(得分:0)

创建一个新对象,表示要从端点返回的数据子集。然后将数据从主体复制到新对象,最后返回新对象。