首页 > 解决方案 > 如何使用 ProtectedPersonalData 属性

问题描述

我找到了 ASP.NET Core Identity 框架的属性类ProtectedPersonalData( link ),但我似乎找不到任何关于如何使用它的文档。文档只说:Used to indicate that a something is considered personal data and should be protected.

最后,我能够加密身份用户类字段(链接)(例如电子邮件字段),但不能加密身份用户继承类的任何属性。

public class ApplicationUser : IdentityUser {

        [ProtectedPersonalData]
        public string MyProperty { get; set; }
}

我将此添加到身份配置中:

services.AddDefaultIdentity<ApplicationUser>(options => {
                options.Stores.ProtectPersonalData = true;
            })
            .AddRoles<IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>();

此外,我实现了保护类:

public class Lookup : ILookupProtector {
            public string Protect(string keyId, string data) {
                return new string(data?.Reverse().ToArray());
            }

            public string Unprotect(string keyId, string data) {
                return new string(data?.Reverse().ToArray());
            }
        }

public class Protector : IPersonalDataProtector {
            public string Protect(string data) {
                return new string(data?.Reverse().ToArray());
            }

            public string Unprotect(string data) {
                return new string(data?.Reverse().ToArray());
            }
        }

public class KeyRing : ILookupProtectorKeyRing {
            public string this[string keyId] => "key";

            public string CurrentKeyId => "key";

            public IEnumerable<string> GetAllKeyIds() {
                return new string[] { "key" };
            }
        }

可以加密MyProperty字段吗?请指出我的信息或提供一些例子。

更新:

我注意到代码永远不会进入Protectproperty 的方法中MyProperty

标签: asp.net-core.net-coreasp.net-identity.net-5

解决方案


您需要将数据注释添加到符合PersonalData条件的属性,如下所示:

[ProtectedPersonalData]
[PersonalData]
public string Firstname { get; set; }

[ProtectedPersonalData]
[PersonalData]
public string Lastname { get; set; }

为了激活您需要在Startup.cs中注册服务的过程:

// ProtectedData
services.AddScoped<ILookupProtectorKeyRing, KeyRing>();
services.AddScoped<ILookupProtector, LookupProtector>();
services.AddScoped<IPersonalDataProtector, PersonalDataProtector>();

示例存储库

在这里,您可以找到一个示例存储库,其中包含具有 Microsoft 身份帐户和ProtectedData实施的 Blazor WASM 项目。

https://github.com/nbiada/protecteddata-wasm-example


推荐阅读