在C# MVC中从ADFS 3.0端点获取Refresh Token的步骤如下:
<configSections>
<section name="system.identityModel" type="System.IdentityModel.Configuration.SystemIdentityModelSection, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<system.identityModel>
<identityConfiguration>
<audienceUris>
<add value="https://your-app-url.com" />
</audienceUris>
<issuerNameRegistry type="System.IdentityModel.Tokens.ValidatingIssuerNameRegistry, System.IdentityModel.Tokens.ValidatingIssuerNameRegistry">
<authority name="https://your-adfs-url/adfs/services/trust">
<keys>
<add thumbprint="your-adfs-thumbprint" />
</keys>
<validIssuers>
<add name="https://your-adfs-url/adfs/services/trust" />
</validIssuers>
</authority>
</issuerNameRegistry>
<certificateValidation certificateValidationMode="None" />
<securityTokenHandlers>
<clear />
<add type="System.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler, System.IdentityModel.Tokens.Saml2, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</securityTokenHandlers>
</identityConfiguration>
</system.identityModel>
请注意替换以下值:
https://your-app-url.com
:你的应用程序的URL。https://your-adfs-url/adfs/services/trust
:你的ADFS的URL。your-adfs-thumbprint
:你的ADFS的证书指纹。System.IdentityModel.Tokens
命名空间中的类来实现。以下是一个示例代码:using System.IdentityModel.Tokens;
public class HomeController : Controller
{
public ActionResult Index()
{
string adfsUrl = "https://your-adfs-url/adfs";
string clientId = "your-client-id";
string redirectUri = "https://your-app-url.com/callback";
string resource = "your-resource";
string authorizationEndpoint = $"{adfsUrl}/oauth2/authorize";
string tokenEndpoint = $"{adfsUrl}/oauth2/token";
string code = Request.QueryString["code"];
if (!string.IsNullOrEmpty(code))
{
TokenClient tokenClient = new TokenClient(tokenEndpoint, clientId, "your-client-secret");
TokenResponse tokenResponse = tokenClient.RequestAuthorizationCodeAsync(code, redirectUri).Result;
string refreshToken = tokenResponse.RefreshToken;
// 在这里可以将Refresh Token保存到数据库或其他持久化存储中
// 其他处理逻辑...
return View();
}
else
{
string authorizationUrl = new RequestUrl(authorizationEndpoint)
.CreateAuthorizeUrl(clientId, "code", redirectUri, responseMode: "form_post", resource: resource);
return Redirect(authorizationUrl);
}
}
}
请注意替换以下值:
https://your-adfs-url/adfs
:你的ADFS的URL。your-client-id
:你的应用程序的客户端ID。https://your-app-url.com/callback
:你的应用程序的回调URL。your-resource
:你要访问的资源。这段代码中,当用户访问首页时,如果没有收到授权码(code),则会重定向到ADFS的授权页面。用户完成授权后,会重定向回应用程序的回调URL,并携带授权码。应用程序使用授权码向ADFS的Token端点请求Refresh Token,并将其保存到适当的位置。
领取专属 10元无门槛券
手把手带您无忧上云