如何在AuthNRequest中添加属性,且用C# itfoxtec-identity-saml2向Assertion加AttributeStatement
1 AuthNRequest添加属性操作方法
使用itfoxtec-identity-saml2库构造认证请求时,直接通过AuthnRequest对象的Attributes集合添加自定义属性即可,示例代码如下:
// 初始化AuthNRequest基础参数 var authnRequest = new AuthnRequest( new Uri("IdP单点登录服务地址"), new EntityId("你的SP实体ID"), new Uri("SP断言消费服务地址") ); // 向AuthNRequest添加属性 authnRequest.Attributes.Add(new SamlAttribute { Name = "属性唯一标识", NameFormat = SamlAttributeNameFormats.Uri, // 可根据需求替换为Basic等其他格式 FriendlyName = "属性友好名称", AttributeValue = "属性值" });
2 Assertion中添加指定AttributeStatement实现
你给出的AttributeStatement结构可以通过构造AttributeStatement对象添加对应属性后,插入断言的Statements集合实现,完整代码如下:
// 初始化SAML断言基础信息 var saml2Assertion = new Saml2Assertion(new EntityId("你的IdP实体ID")) { Subject = new Subject(new NameId("用户唯一标识") { Format = NameIdFormats.Persistent // 可根据需求调整NameID格式 }), Conditions = new Conditions( notBefore: DateTimeOffset.UtcNow, notOnOrAfter: DateTimeOffset.UtcNow.AddMinutes(10) // 断言有效期按实际需求配置 ) }; // 构造符合要求的AttributeStatement var attributeStatement = new AttributeStatement(); // 添加SurName属性 attributeStatement.Attributes.Add(new SamlAttribute { FriendlyName = "SurName", Name = "urn:oid:2.5.4.4", NameFormat = SamlAttributeNameFormats.Uri, AttributeValue = "Max" }); // 添加CommonName属性 attributeStatement.Attributes.Add(new SamlAttribute { FriendlyName = "CommonName", Name = "urn:oid:2.5.4.3", NameFormat = SamlAttributeNameFormats.Uri, AttributeValue = "Max Mustermann" }); // 添加无友好名的属性 attributeStatement.Attributes.Add(new SamlAttribute { Name = "urn:oid:0.9.2342.19200300.100.1.1", NameFormat = SamlAttributeNameFormats.Uri, AttributeValue = "has" }); // 添加Email属性 attributeStatement.Attributes.Add(new SamlAttribute { FriendlyName = "Email", Name = "urn:oid:0.9.2342.19200300.100.1.3", NameFormat = SamlAttributeNameFormats.Uri, AttributeValue = "max@mustermann.de" }); // 将AttributeStatement加入断言 saml2Assertion.Statements.Add(attributeStatement);
补充说明
- 生成的断言属性结构和你给出的示例完全一致,字符串类型的属性值会自动生成
xsi:type="xs:string"标记,无需额外配置 - 若你是SP侧接收断言,无需手动构造AttributeStatement,可直接从
Saml2AuthnResponse.Assertion.Statements中筛选类型为AttributeStatement的节点读取属性值
内容的提问来源于stack exchange,提问作者Franz Ehrenhuber
相关产品推荐
相关产品推荐

