Skip to content

Commit e996795

Browse files
committed
针对PR #135 中提到的问题进行了修改
1 parent b37d105 commit e996795

File tree

6 files changed

+36
-38
lines changed

6 files changed

+36
-38
lines changed

PCL.Neo.Core/Service/Accounts/MicrosoftAuth/DeviceCodeData.cs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,14 @@
1+
using System.Text.Json.Serialization;
2+
13
namespace PCL.Neo.Core.Service.Accounts.MicrosoftAuth;
24

35
public static class DeviceCodeData
46
{
5-
public record DeviceCodeInfo(string device_code, string user_code, string verification_uri, int interval);
7+
public record DeviceCodeInfo(
8+
[property: JsonPropertyName("device_code")] string DeviceCode,
9+
[property: JsonPropertyName("user_code")] string UserCode,
10+
[property: JsonPropertyName("verification_uri")] string VerificationUri,
11+
[property: JsonPropertyName("interval")] int Interval);
612

713
public record DeviceCodeAccessToken(string AccessToken, string RefreshToken, DateTimeOffset ExpiresIn);
814

PCL.Neo.Core/Service/Accounts/MicrosoftAuth/MicrosoftAuthService.cs

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
using Flurl.Http;
2-
using Microsoft.Extensions.Configuration;
32
using PCL.Neo.Core.Service.Accounts.Exceptions;
43
using PCL.Neo.Core.Service.Accounts.OAuthService;
54
using PCL.Neo.Core.Service.Accounts.OAuthService.Exceptions;
@@ -10,7 +9,6 @@
109
using System.Reactive.Linq;
1110
using System.Text;
1211
using System.Text.Json;
13-
using System.Threading;
1412

1513
namespace PCL.Neo.Core.Service.Accounts.MicrosoftAuth;
1614

@@ -31,16 +29,16 @@ public IObservable<DeviceFlowState> StartDeviceCodeFlow() => Observable.Create<D
3129
var deviceCodeInfo = deviceCodeResult.Value;
3230

3331
// show for user 将流式验证要输入的验证码返回给观察者
34-
observer.OnNext(new DeviceFlowAwaitUser(deviceCodeInfo.user_code, deviceCodeInfo.verification_uri));
32+
observer.OnNext(new DeviceFlowAwaitUser(deviceCodeInfo.UserCode, deviceCodeInfo.VerificationUri));
3533

3634
// polling server 等待验证信息
37-
var tokenResult = await PollForTokenAsync(deviceCodeInfo.device_code, deviceCodeInfo.interval)
35+
var tokenResult = await PollForTokenAsync(deviceCodeInfo.DeviceCode, deviceCodeInfo.Interval)
3836
.ConfigureAwait(false);
3937
observer.OnNext(new DeviceFlowPolling());
4038
// Failed 验证失败后直接返回错误
4139
if (tokenResult.IsFailure)
4240
{
43-
observer.OnNext(tokenResult.Error);
41+
observer.OnError(tokenResult.Error.Exc);
4442
return;
4543
}
4644
//验证成功后继续获取MC玩家数据
@@ -94,15 +92,15 @@ public IObservable<DeviceFlowState> StartDeviceCodeFlow() => Observable.Create<D
9492
{
9593
["client_id"] = OAuthData.FormUrlReqData.Configurations.ClientId,
9694
["tenant"] = "/consumers",
97-
["scope"] = string.Join(" ", _scopes)
95+
["scope"] = string.Join(' ', _scopes)
9896
};
9997
var request = Net.Request("https://login.microsoftonline.com/consumers/oauth2/v2.0/devicecode");
10098
string json = await request.PostUrlEncodedAsync(parameters).ReceiveString();
10199
var temp = JsonSerializer.Deserialize<DeviceCodeData.DeviceCodeInfo>(json);
102100
/* 返回400
103101
var temp = await Net.SendHttpRequestAsync<DeviceCodeData.DeviceCodeInfo>(HttpMethod.Post,
104102
OAuthData.RequestUrls.DeviceCode.Value, content).ConfigureAwait(false); */
105-
var result = new DeviceCodeData.DeviceCodeInfo(temp.device_code, temp.user_code, temp.verification_uri,temp.interval);
103+
var result = new DeviceCodeData.DeviceCodeInfo(temp.DeviceCode, temp.UserCode, temp.VerificationUri,temp.Interval);
106104
return Result<DeviceCodeData.DeviceCodeInfo, HttpError>.Ok(result);
107105
}
108106
catch (HttpRequestException e)

PCL.Neo.Core/Service/Accounts/OAuthService/OAuth.cs

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -44,25 +44,15 @@ public static class OAuth
4444
TokenType = "JWT"
4545
};
4646
var request = Net.Request("https://user.auth.xboxlive.com/user/authenticate");
47-
4847
/*var result = await Net.SendHttpRequestAsync<OAuthData.ResponseData.XboxResponse>(
4948
HttpMethod.Post,
5049
OAuthData.RequestUrls.XboxLiveAuth.Value,
5150
jsonContent);*/
52-
try
53-
{
54-
var b = JsonSerializer.Serialize(xblContent);
55-
var xblJsonReq = await request.PostAsync(new StringContent(b,Encoding.UTF8, "application/json"));
56-
var temp = await xblJsonReq.GetStringAsync();
57-
var result = JsonSerializer.Deserialize<OAuthData.ResponseData.XboxResponse>(temp);
58-
return result;
59-
}
60-
catch(Exception ex)
61-
{
62-
throw ex;
63-
}
64-
65-
51+
var b = JsonSerializer.Serialize(xblContent);
52+
var xblJsonReq = await request.PostAsync(new StringContent(b, Encoding.UTF8, "application/json"));
53+
var temp = await xblJsonReq.GetStringAsync();
54+
var result = JsonSerializer.Deserialize<OAuthData.ResponseData.XboxResponse>(temp);
55+
return result;
6656
}
6757

6858
[DynamicDependency(DynamicallyAccessedMemberTypes.PublicConstructors, typeof(OAuthData.RequireData))]
@@ -95,13 +85,11 @@ public static async Task<string> GetMinecraftTokenAsync(string accessToken)
9585
var xboxToken = await GetXboxTokenAsync(accessToken);
9686
var xstsToken = await GetXstsTokenAsync(xboxToken.Token);
9787
var minecraftAccessToken =
98-
await MinecraftInfo.GetMinecraftAccessTokenAsync(xboxToken.DisplayClaims.Xui.First().Uhs, xstsToken);
99-
88+
await MinecraftInfo.GetMinecraftAccessTokenAsync(xboxToken.DisplayClaims.Xui.First().Uhs, xstsToken);
10089
if (!await MinecraftInfo.IsHaveGameAsync(minecraftAccessToken))
10190
{
10291
throw new NotHaveGameException("Logged-in user does not own any game!");
10392
}
104-
10593
return minecraftAccessToken;
10694
}
10795

PCL.Neo.Core/Service/Accounts/OAuthService/OAuthData.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ public static class FormUrlReqData
6969
//private static OAuth2Configurations Configurations => _configurations ??= ConfigurationManager.Instance.GetConfiguration<OAuth2Configurations>();
7070
public static OAuth2Configurations Configurations = new OAuth2Configurations()
7171
{
72-
ClientId = "12345678-1234-1234-1234-abcdefghijkl",//自己申请去
72+
ClientId = "12345678-1234-1234-1234-abcdefghijkl",//TODO:需要一个能正常使用的ClientID
7373
};
7474
/// <summary>
7575
/// 获取授权码的地址

PCL.Neo.Core/Utils/Net.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ public static IFlurlClient Initialize(IFlurlClient client = default)
5151
/// <param name="content">请求内容</param>
5252
/// <param name="bearerToken"></param>
5353
/// <returns></returns>
54+
[Obsolete]
5455
public static async Task<TResponse> SendHttpRequestAsync<TResponse>(
5556
HttpMethod method,
5657
Uri url,

PCL.Neo/ViewModels/HomeViewModel.cs

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
using PCL.Neo.Helpers;
1313
using PCL.Neo.Models.User;
1414
using PCL.Neo.Services;
15+
using PCL.Neo.Utils;
1516
using PCL.Neo.ViewModels.Home;
1617
using PCL.Neo.Views;
1718
using SkiaSharp;
@@ -139,6 +140,8 @@ private async Task AddMicrosoftUser()
139140
{
140141
MicrosoftAuthService microsoftAuthService = new MicrosoftAuthService();
141142
var result = microsoftAuthService.StartDeviceCodeFlow();
143+
Logger.InitLogger(@".\");
144+
var log = Logger.GetInstance();
142145
result.Subscribe(
143146
onNext: async state =>
144147
{
@@ -153,57 +156,59 @@ private async Task AddMicrosoftUser()
153156
var launcher = topLevel.Launcher;
154157
await clipboard.SetTextAsync(awaitUser.UserCode);
155158
await launcher.LaunchUriAsync(new Uri(awaitUser.VerificationUri));
159+
log.Log($"请访问 {awaitUser.VerificationUri} 并输入代码: {awaitUser.UserCode}", Logger.LogLevel.Msgbox);
156160
}
157161
break;
158162

159163
case DeviceFlowPolling:
160-
Debug.WriteLine("正在轮询服务器,等待用户验证...");
164+
log.Log("正在轮询服务器,等待用户验证...");
161165
break;
162166

163167
case DeviceFlowDeclined:
164-
Debug.WriteLine("用户拒绝了授权请求。");
168+
log.Log("用户拒绝了授权请求。");
165169
break;
166170

167171
case DeviceFlowExpired:
168-
Debug.WriteLine("设备代码已过期,请重新启动验证流程。");
172+
log.Log("设备代码已过期,请重新启动验证流程。", Logger.LogLevel.Msgbox);
169173
break;
170174

171175
case DeviceFlowBadVerificationCode:
172-
Debug.WriteLine("验证码无效,请检查后重试。");
176+
log.Log("验证码无效,请检查后重试。", Logger.LogLevel.Msgbox);
173177
break;
174178

175179
case DeviceFlowGetAccountInfo:
176-
Debug.WriteLine("正在获取 Minecraft 账户信息...");
180+
log.Log("正在获取 Minecraft 账户信息...");
177181
break;
178182

179183
case DeviceFlowSucceeded success:
184+
log.Log($"登录成功!用户名: {success.Account.UserName}");
180185
UpdateCurrentUserInfo(new(success.Account));
181186
break;
182187

183188
case DeviceFlowInternetError:
184-
Debug.WriteLine("网络错误,请检查连接后重试。");
189+
log.Log("网络错误,请检查连接后重试。", Logger.LogLevel.Msgbox);
185190
break;
186191

187192
case DeviceFlowJsonError:
188-
Debug.WriteLine("服务器返回的数据格式错误,可能是 API 变更。");
193+
log.Log("服务器返回的数据格式错误,可能是 API 变更。", Logger.LogLevel.Msgbox);
189194
break;
190195

191196
case DeviceFlowUnkonw:
192-
Debug.WriteLine("未知错误,请查看日志。");
197+
log.Log("未知错误,请查看日志。", Logger.LogLevel.Msgbox);
193198
break;
194199

195200
default:
196-
Debug.WriteLine($"收到未处理的状态: {state.GetType().Name}");
201+
log.Log($"收到未处理的状态: {state.GetType().Name}", Logger.LogLevel.Msgbox);
197202
break;
198203
}
199204
},
200205
onError: error =>
201206
{
202-
Debug.WriteLine($"发生未捕获的错误: {error.Message}");
207+
log.Log($"发生未捕获的错误: {error.Message}", Logger.LogLevel.Msgbox);
203208
},
204209
onCompleted: () =>
205210
{
206-
Debug.WriteLine("验证流程已完成(成功或不可恢复的错误)。");
211+
log.Log("验证流程已完成(成功或不可恢复的错误)。", Logger.LogLevel.Msgbox);
207212
}
208213
);
209214
}

0 commit comments

Comments
 (0)