【问题标题】:How I can get current user's email from keycloak in jhipster如何从 jhipster 中的 keycloak 获取当前用户的电子邮件
【发布时间】:2019-09-30 01:35:13
【问题描述】:

我用 ouath 2.0 配置了 jhipster,它使用 keycloak 作为授权服务器。但是如何在我的应用中获取当前用户的电子邮件?

【问题讨论】:

    标签: spring-security oauth-2.0 jhipster keycloak


    【解决方案1】:

    一种方法是使用 AccountService

    在您的组件中,您将执行如下所示的操作。您需要更改值以匹配您的项目

    // Add these imports
    import { AccountService } from 'app/core/auth/account.service';
    import { Account } from 'app/core/auth/account.model';
    
    @Component({
       selector: 'jhi-pm-your-project-update',
       templateUrl: './pm-your-project-update.component.html',
     })
    
     export class YourUpdateComponent implements Oninit{
        // Add this varable to store the account information
        account: Account | null = null;
    
        constructor(
          protected dataUtils: DataUtils,
          protected eventManager: EventManager,
          protected yourService: YourService,
          protected activatedRoute: ActivatedRoute,
          protected accountService: AccountService
         ){}
              
    
        ngOnInit(): void {
          this.accountService.identity().subscribe(account => (this.account = account));
     
        }
    
    
        save(): void {
          // Here is how to access the email
          yourEntity.lastModifiedBy = this.account?.email;
       
        } 
    

    }

    【讨论】:

      【解决方案2】:

      当用户通过 OAuth2 登录时,帐号is synchronized to the local user database

      在您的应用程序中存在SecurityUtils.java,它具有获取当前用户登录名的方法。您可以获取用户/电子邮件的登录和查询。

      String login = SecurityUtils.getCurrentUserLogin().orElse("anonymoususer");
      Optional<User> optionalUser = userService.getUserWithAuthoritiesByLogin(login);
      if (optionalUser.isPresent()) {
          String email = optionalUser.get().getEmail();
      }
      

      【讨论】:

      • 在我的本地电脑和用户管理员上使用默认安装(我使用keycloak和注册表的docker镜像),它返回null;
      • 无法复现,将账号存入本地数据库后,信息返回正确。我添加了一行来记录结果并查看电子邮件,例如c.m.myapp.web.rest.AccountResource : admin@localhost
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-09
      • 1970-01-01
      • 2022-09-23
      • 2018-10-09
      • 1970-01-01
      • 2014-05-09
      • 2018-12-13
      相关资源
      最近更新 更多