我需要将 SAML 身份验证添加到我的 Web 应用程序(WebAPI 后端/角度前端),并将 Azure AD 作为我的身份提供者。
我计划使用 Sustainsys.Saml2 库,但我不确定如何正确使用该库提供的方法。
我已经将我的 Web 应用程序添加为 Azure AD 上的企业应用程序,并执行了必要的 SSO SAML 配置。
我在 web.config 中配置了sustainsys,如下所示:
<sustainsys.saml2 entityId="https://myWebApp/api/saml/login" returnUrl="https://myWebApp/">
<identityProviders>
<add
entityId="https://sts.windows.net/36tg486z-9l1f/"
signOnUrl="https://login.microsoftonline.com/36tg486z-9l1f/saml2"
metadataLocation="https://login.microsoftonline.com/36tg486z-9l1f/federationmetadata/2007-06/federationmetadata.xml?appid=82fc2g56-2as2"
allowUnsolicitedAuthnResponse="true"
loadMetadata="true"
binding="HttpPost"
>
</add>
</identityProviders>
<serviceCertificates>
<add fileName="~/App_Data/Sustainsys.Saml2.Tests.pfx" />
</serviceCertificates>
</sustainsys.saml2>
我的想法是编写两个 API:
1 - 执行登录到 Azure AD 的 API:
[HttpGet]
[Route("api/saml/signIn")]
[ResponseType(typeof(void))]
public HttpResponseMessage SignIn()
{
var context = new HttpContextWrapper(HttpContext.Current);
HttpRequestBase request = context.Request;
var opt = Sustainsys.Saml2.Configuration.Options.FromConfiguration;
var result = CommandFactory.GetCommand(CommandFactory.SignInCommandName).Run(request.ToHttpRequestData(), opt);
var response = Request.CreateResponse(result.HttpStatusCode);
if (!string.IsNullOrEmpty(result.SetCookieName))
{
var protectedData = HttpRequestData.ConvertBinaryData(MachineKey.Protect(result.GetSerializedRequestState(),HttpRequestBaseExtensions.ProtectionPurpose));
var cookie = new CookieHeaderValue(result.SetCookieName, protectedData) { HttpOnly = true };
var cookies = new List<CookieHeaderValue>() { cookie };
response.Headers.AddCookies(cookies);
}
response.Headers.Location = result.Location;
return response;
}
2 - 接收来自 Azure AD 的响应并读取 SAML 令牌内的声明的 API:
[HttpPost]
[Route("api/saml/acs")]
[ResponseType(typeof(result))]
public HttpResponseMessage Acs()
{
var context = new HttpContextWrapper(HttpContext.Current);
HttpRequestBase request = context.Request;
var opt = Sustainsys.Saml2.Configuration.Options.FromConfiguration;
var result = CommandFactory.GetCommand(CommandFactory.AcsCommandName).Run(request.ToHttpRequestData(), opt);
// ... read claims ...
// ... build [LoginResult] with claims ...
var response = Request.CreateResponse(result.HttpStatusCode, [LoginResult]);
response.Headers.Location = new Uri(result.Location.AbsoluteUri);
return response;
}
这是使用 SustainSys 添加 SAML 身份验证的正确方法吗?