過往都使用傳統的.Net framework做開發, 這次手上拿到一個新專案想嘗試一些不一樣的
IDE工具: Visual Studio 2022
採用 React.js + .Net 6
在導入Windows驗證機制的時候出現問題, 參考microsoft和網路其他大神的解法卻還是有些問題, 認為是自己對於前後端架構的理解有誤
https://learn.microsoft.com/zh-tw/aspnet/core/security/authentication/windowsauth?view=aspnetcore-6.0&tabs=visual-studio
在Program.cs加上Windows驗證的設定,並切換IDE的模擬環境至IIS Express後
專案可以正常運行
但在fetch後端api的時候出現401.2的Error
如果直接在URL上面輸入https://localhost:*****/weatherforecast
則可以成功打到後端controller,並取得Windows驗證的身分資訊
若不啟用Windows驗證的話,專案就可以正常的打到後端controller並取得資訊
想請教是哪個部份的專案設定錯了呢?
謝謝
-以下是專案目前的部分程式碼-
專案設定檔
setupProxy.js
...
module.exports = function(app) {
const appProxy = createProxyMiddleware(context, {
target: target,
secure: false,
headers: {
Connection: 'Keep-Alive'
}
});
app.use(appProxy);
};
launchSetting.json
{
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false,
"iisExpress": {
"applicationUrl": "http://localhost:*****",
"sslPort": *****
}
}
}
Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(IISDefaults.AuthenticationScheme);
...
app.UseAuthentication();
app.UseAuthorization();
fetchData.js
...
componentDidMount() {
this.populateWeatherData();
}
...
async populateWeatherData() {
const response = await fetch('weatherforecast');
const data = await response.json();
this.setState({ forecasts: data, loading: false });
}
WeatherForecastController
[ApiController]
[Route("[controller]")]
[AuthorizeF]
public class WeatherForecastController : ControllerBase
{
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var user = HttpContext.User?.Identity?.Name ?? "N/A";
return Enumerable.Range(1, 5).Select(index => new WeatherForecastViewModel
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}