You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 8 Blazor集成Microsoft Identity:获取当前用户自定义属性

获取当前登录用户自定义属性的方案

核心思路

所有方案的核心逻辑统一为:

  1. 提取当前登录用户的唯一标识(通常为用户ID)
  2. 通过该标识查询存储自定义属性的数据源(如关联数据库表、用户扩展集合等)

常见技术栈实现示例

1. ASP.NET Core

通过HttpContext.User获取用户Claims提取ID,再查询关联的自定义属性存储:

// 从Claims中获取当前用户ID
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);

// 假设用EF Core查询存储自定义属性的UserProfile表
var userProfile = await _dbContext.UserProfiles.FirstOrDefaultAsync(u => u.UserId == userId);

// 读取自定义属性
var userAddress = userProfile?.Address;
var userBirthDate = userProfile?.BirthDate;

2. Django

利用request.user获取当前用户实例,直接访问关联的Profile模型属性:

from django.contrib.auth.decorators import login_required

@login_required
def get_custom_user_attrs(request):
    # 访问与User模型一对一关联的Profile实例
    user_profile = request.user.profile
    # 读取自定义字段
    custom_preference = user_profile.notification_preference
    custom_bio = user_profile.bio
    return ...

3. Node.js (Express + Passport)

当前用户挂载在req.user上,提取ID后查询MongoDB中的用户扩展集合:

// 假设用Mongoose操作数据库
app.get('/user/custom-attributes', (req, res) => {
  const userId = req.user._id;
  
  UserProfile.findOne({ userId: userId })
    .then(profile => {
      const customAttr = profile?.favorite_category;
      res.send({ customAttr });
    })
    .catch(err => res.status(500).send(err));
});

注意事项

  • 确保自定义属性与用户ID关联存储,可选择单独的用户扩展表或在主用户表新增字段
  • 必须添加登录校验,避免未授权用户查询他人属性
  • 若频繁调用,可将常用自定义属性缓存到用户会话或JWT Payload中,减少数据库查询次数

内容的提问来源于stack exchange,提问作者Systellence

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 14:40:56