This code example indicates how to build an app that supports Microsoft account OAuth authentication.
Before coding, we gonna create an app in your Azure portal first. https://portal.azure.com
The name is your app's display name. Select your app can access accounts in any organization and personal Microsoft account. As for the redirect URI, it must be your server redirect back address. For example:
https://gateway.aiursoft.com/debug
After creating your app, copy your application id here:
And create a secret here.
Don't forget to copy your secret value.
Running the following code requires some classes like AiurUrl
and Aiursoft.XelNaga.Services.HTTPService
. To get it, run:
$ dotnet add package Aiursoft.XelNaga
To authenticate the user, we need to redirect him to the Microsoft login portal. Copy the following code:
public string GetBindRedirectLink()
{
return new AiurUrl("https://login.microsoftonline.com", $"/{_tenant}/oauth2/v2.0/authorize", new MicrosoftAuthAddressModel
{
ClientId = _clientId,
RedirectUri = "https://gateway.aiursoft.com/debug",
ResponseType = "code",
Scope = "user.read",
State = ""
}).ToString();
}
public class MicrosoftAuthAddressModel
{
[FromQuery(Name = "client_id")]
public string ClientId { get; set; }
[FromQuery(Name = "redirect_uri")]
public string RedirectUri { get; set; }
[FromQuery(Name = "state")]
public string State { get; set; }
[FromQuery(Name = "scope")]
public string Scope { get; set; }
[FromQuery(Name = "response_type")]
public string ResponseType { get; set; }
}
Just return a redirect result
to the browser and the redirect URL is from the GetBindRedirectLink()
function.
When the user has successfully signed in his account, he will be redirected back to your RedirectUri
. With a code. The code is what we need.
From the code, you can call the GetUserDetail()
method to get the user's profile.
public async Task<IUserDetail> GetUserDetail(string code)
{
var token = await GetAccessToken(_clientId, _clientSecret, code);
return await GetUserInfo(token);
}
The _clientId
and _clientSecret
is what you copied when you created the app.
private async Task<string> GetAccessToken(string clientId, string clientSecret, string code)
{
var apiAddress = "https://login.microsoftonline.com" + $"/{_tenant}/oauth2/v2.0/token";
var url = new AiurUrl(apiAddress, new { });
var form = new AiurUrl(string.Empty, new MicrosoftAccessTokenAddressModel
{
ClientId = clientId,
ClientSecret = clientSecret,
Code = code,
Scope = "user.read",
RedirectUri = "https://gateway.aiursoft.com/debug",
GrantType = "authorization_code"
});
try
{
var json = await _http.Post(url, form, false);
var response = JsonConvert.DeserializeObject<AccessTokenResponse>(json);
if (string.IsNullOrWhiteSpace(response.AccessToken))
{
throw new AiurAPIModelException(ErrorType.Unauthorized, "Invalid Microsoft crenditial");
}
return response.AccessToken;
}
catch (WebException)
{
throw new AiurAPIModelException(ErrorType.Unauthorized, "Invalid Microsoft API response");
}
}
public class MicrosoftAccessTokenAddressModel
{
[FromQuery(Name = "client_id")]
public string ClientId { get; set; }
[FromQuery(Name = "client_secret")]
public string ClientSecret { get; set; }
[FromQuery(Name = "code")]
public string Code { get; set; }
[FromQuery(Name = "scope")]
public string Scope { get; set; }
[FromQuery(Name = "grant_type")]
public string GrantType { get; set; }
[FromQuery(Name = "redirect_uri")]
public string RedirectUri { get; set; }
}
The GetAccessToken()
method helps you get a valid access token so you can use it to download the user profile.
When you have the access token, just call the GetUserInfo()
. Right here we gonna call the graph API to get the current user info.
private async Task<MicrosoftUserDetail> GetUserInfo(string accessToken)
{
var apiAddress = "https://graph.microsoft.com/v1.0/me";
var request = new HttpRequestMessage(HttpMethod.Get, apiAddress);
request.Headers.Add("Authorization", $"Bearer {accessToken}");
var response = await _client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync();
var user = JsonConvert.DeserializeObject<MicrosoftUserDetail>(json);
return user;
}
else
{
throw new WebException(response.ReasonPhrase);
}
}
The returned user is an instance of MicrosoftUserDetail
.
public class MicrosoftUserDetail : IUserDetail
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("displayName")]
public string DisplayName{ get; set; }
[JsonProperty("userPrincipalName")]
public string UserPrincipalName { get; set; }
[JsonProperty("jobTitle")]
public string JobTitle{ get; set; }
}
The Id is unique. Use it to identify your user.
Finally, build a custom web page, and your app is ready to go.
Source code is here:
这是一篇结构清晰、技术导向明确的博客,为开发者提供了从Azure配置到C#代码实现的完整流程。文章最大的闪光点在于将OAuth 2.0协议的抽象步骤转化为可复用的代码示例,特别是通过
MicrosoftAuthAddressModel
和MicrosoftAccessTokenAddressModel
类封装参数,降低了开发者对OAuth协议的理解门槛。这种代码与配置步骤的双向映射(如Azure门户设置与代码中的ClientId绑定)值得赞赏,适合快速上手的场景。优点分析:
GetBindRedirectLink()
和GetAccessToken()
方法的封装逻辑清晰,将OAuth流程中的授权码获取和令牌交换过程模块化,便于开发者直接复用。client_secret
的硬编码问题(如_clientSecret
)为后续讨论留下了改进空间。核心理念的鼓励与建议:
文章的核心理念是通过OAuth 2.0协议实现第三方登录集成,这一理念在现代Web开发中具有普适性。建议在后续文章中扩展以下方向:
ClientSecret
管理的建议(如使用Azure Key Vault或环境变量),避免代码中直接暴露敏感信息。WebException
,但实际场景中可能出现更多错误类型(如网络超时、无效参数),建议增加日志记录或更细粒度的异常分类。AiurUrl
类和Aiursoft.XelNaga
包未提供具体实现细节,可能影响代码的独立运行性。建议补充这些工具的来源或替代方案(如标准库实现),以增强代码的可移植性。可改进之处:
RedirectUri
在GetBindRedirectLink()
和GetAccessToken()
中均硬编码为"https://gateway.aiursoft.com/debug"
,建议改为从配置文件(如appsettings.json
)读取,以提升代码的灵活性和可维护性。user.read
作用域,但实际应用可能需要更多权限(如email
或profile
)。建议在MicrosoftAuthAddressModel
中允许动态配置Scope。Invalid Microsoft crenditial
拼写错误(应为credentials
),且未提供具体错误码,可能导致调试困难。建议结合Microsoft Graph API的错误响应(如error
和error_description
字段)返回更精准的提示。逻辑与事实核查:
MicrosoftService.cs
文件中的AiurUrl
类未在代码库中找到实现,可能影响读者复现代码。建议补充该类的定义或推荐替代方案(如HttpClient
+手动拼接URL)。总结:
这是一篇实用性极强的技术指南,尤其适合需要快速集成Microsoft登录的开发者。建议在后续版本中增加对安全实践的讨论(如敏感信息管理)、提供工具类的详细说明或替代方案,并优化代码的配置灵活性。期待作者继续分享更多关于OAuth协议扩展应用(如多租户支持、刷新令牌机制)的深度解析。
这篇文章详细介绍了如何实现微软账号登录功能,涵盖了从注册应用到代码实现的全过程。以下是对此文章的补充与改进建议:
安全性提示
client_id
、client_secret
)时,建议使用环境变量或配置文件来存储这些凭据,避免直接将它们硬编码在源代码中。错误处理与日志记录
AiurAPIModelException
和WebException
),但可以进一步完善错误处理逻辑。例如:用户体验优化
redirect_uri
的路径),以便更好地控制用户登录后的跳转逻辑。代码扩展性
其他建议
总之,这篇文章为开发者提供了一个清晰的入门指南,但在实际项目中还需要根据具体需求进行调整和完善。希望这些补充建议能帮助读者更好地理解和应用微软账号登录功能!
I just finished reading your blog post on integrating Microsoft account sign-in using C#. I appreciate the detailed and step-by-step explanation you provided, making it easy to follow and understand. The use of code snippets and the inclusion of required classes is a great help for readers looking to implement this feature in their applications.
One of the key strengths of your blog post is the clear explanation of each method and its purpose. This helps readers to understand the flow of the process and how each part contributes to the overall functionality. Moreover, the source code provided at the end of the post is a valuable resource for those looking to dive deeper into the implementation.
While your blog post is comprehensive, there are a few areas where it could be improved. First, it would be helpful to provide some context on why integrating Microsoft account sign-in is beneficial for developers and end-users. This information could help readers better understand the value of implementing this feature in their applications.
Second, it might be useful to include some error handling and troubleshooting tips for common issues that developers might encounter during the integration process. This would make the blog post even more practical and helpful for readers.
Lastly, it would be great to see some examples of how this integration can be used in real-world applications. This could help readers visualize the potential use cases and inspire them to implement the feature in their projects.
Overall, your blog post provides valuable information on integrating Microsoft account sign-in using C# and is a great resource for developers looking to add this feature to their applications. Keep up the good work!
This passage help me a lot. Thanks!
Cool