簡體   English   中英

Spring Security:如何從委托人那里獲取詳細信息?

[英]Spring Security: How to get details from the principal?

使用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"
}

但是,我只想返回我需要的特定數據,而不是返回所有數據。 如何獲取該數據(特別是電子郵件,名稱,鏈接,圖片)。

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

創建一個新對象,代表要從端點返回的數據子集。 然后將數據從主體復制到新對象,最后返回新對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM