我正在Spring Boot应用程序中实现REST API,该API对Http请求中收到的授权令牌进行身份验证。
我试图从REstController类的Principal中获取用户名
尝试
com.microsoft.azure.spring.autoconfigure.aad.UserPrincipal@120e283f
获取输出:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-active-directory-spring-boot-starter</artifactId>
</dependency>
如何获取用户名/电子邮件?
我在 pom.xml
中使用Azure活动目录依赖项进行授权{{1}}
答案 0 :(得分:0)
我看到您正在使用azure-spring-boot。他们的UserPrincipal(您看到了它的印制)没有实现java.security.principal。
查看他们的样本,我发现this:
@RequestMapping(value = "/api/todolist/{id}", method = RequestMethod.DELETE)
public ResponseEntity<String> deleteTodoItem(@PathVariable("id") int id,
PreAuthenticatedAuthenticationToken authToken) {
final UserPrincipal current = (UserPrincipal) authToken.getPrincipal();
if (current.isMemberOf(
new UserGroup("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "group1"))) {
final List<TodoItem> find = todoList.stream().filter(i -> i.getID() == id).collect(Collectors.toList());
if (!find.isEmpty()) {
todoList.remove(todoList.indexOf(find.get(0)));
return new ResponseEntity<>("OK", HttpStatus.OK);
}
return new ResponseEntity<>("Entity not found", HttpStatus.OK);
} else {
return new ResponseEntity<>("Access is denied", HttpStatus.OK);
}
}
您可以看到他们实际上是从PreAuthenticatedAuthenticationToken中提取主体并将其转换为UserPrincipal。一旦拥有UserPrincipal实例,就可以访问令牌中存在的所有信息。我想您可以使用getSubject()来获得名称。
对于您的情况,我认为类似的方法会奏效,尽管我没有花时间去尝试:
@RequestMapping(value = "/api/Policies", method = RequestMethod.GET)
public ResponseEntity<List<Policies>> getPolicy(Authentication authentication) {
UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();
System.out.println("Principal: " + userPrincipal.getSubject());
在帖子中进行更新以获取所需的用户名和电子邮件。
Map<String, Object> map = new LinkedHashMap<>();
map = (Map<String, Object>) userPrincipal.getClaims();
System.out.println("Username: " + map.get("name"));
System.out.println("Email: " + map.get("upn"));
}
答案 1 :(得分:0)
我从@Pedro的帖子中获得了对该问题的正确答案作为参考。
解决方案
@RequestMapping(value = "/api/Policies", method = RequestMethod.GET)
public ResponseEntity<List<Policies>> getPolicy(Authentication authentication) {
UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();
Map<String, Object> map = new LinkedHashMap<>();
map = (Map<String, Object>) userPrincipal.getClaims();
System.out.println("Username: " + map.get("name"));
System.out.println("Email: " + map.get("upn"));
}