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

35g0bw71  于 2023-02-23  发布在  Spring
关注(0)|答案(3)|浏览(121)

使用 Boot 和springsecurity,用户的详细信息可以在主体对象中获得,但是它只有很少的方法来获取详细信息,比如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"
}

但是我不想返回所有的数据,我只想返回我需要的特定数据。我如何获得这些数据(具体来说是电子邮件、姓名、链接、图片)?

yptwkmov

yptwkmov1#

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);
    }
}
laximzn5

laximzn52#

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

sdnqo3pr

sdnqo3pr3#

对于开发人员搜索类似的事情...我有一个问题,写我的不和谐登录功能,我是高和低的谷歌...
因此,使用一些职位从这里我提出我的解决方案给你下面。

@GetMapping("/profile")
public String getProfilePage(Principal principal, Model model) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    // If the user requesting this page, is not an anonymous user
    if (!(authentication instanceof AnonymousAuthenticationToken)) {
        // parse the user for some basic information
        parseAuthorizedUser(authentication);
        return "profile";
    }
}

parseAuthorizedUser取自上面的答案之一,并使用SimpleJson

<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>

我能够进行身份验证,并且在我的例子中,循环访问权限,对于每个OAuth2UserAuthority,我确保检查我的用户角色,然后将权限分解为JSON对象,然后只选择权限的属性,并将其Map到一个JSON对象,然后我只是确保它不是null或空的...最后只是设置一些我在其他地方使用的atomicRefs

private void parseAuthorizedUser(Authentication authentication) {
    // ... some previous code for profile basics
    authentication.getAuthorities().forEach(oAuth2UserAuthority ->  {
        if (Objects.equals("ROLE_USER", oAuth2UserAuthority.getAuthority())) {
            try {
                String jsonAttributes = JsonUtil.getObjectAsJson(oAuth2UserAuthority);
                JSONObject jsonObject = (JSONObject) new JSONParser().parse(jsonAttributes);
                if (Objects.nonNull(jsonObject)) {
                    JSONObject userAttributes = (JSONObject) jsonObject.get("attributes");
                    if (Objects.nonNull(userAttributes) && !userAttributes.isEmpty()) {
                        discordId.set(userAttributes.get("id").toString());
                        discordAvatar.set(userAttributes.get("avatar").toString());
                    }
                }
            } catch (JsonProcessingException | ParseException e) {
                throw new RuntimeException(e);
            }
        }
    });
    // ... continue on with the rest of the method
}

至于提到的JsonUtil.getObjectAsJson(Object)这是我使用的方法

public static String getObjectAsJson(Object object) throws JsonProcessingException {
    return new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(object);
}

这是一个模糊的概念,可能会给你沿着正确的道路。

相关问题