1. 配置IIS以使用Windows身份验证
1.打开IIS管理器:
- 打开IIS管理器,选择您的站点。
2.配置身份验证:
- 在站点的“功能视图”中,找到“身份验证”。
- 禁用“匿名身份验证”。
- 启用“Windows身份验证”。
3.确保其他身份验证方法被禁用:
- 确保除了Windows身份验证外,其他身份验证方法(如基本身份验证、摘要身份验证等)都被禁用。
2. 配置.NET Core后端以处理Windows身份验证
1.启用Windows身份验证:
- 在.NET Core应用中,您需要在
Startup.cs文件中启用Windows身份验证。
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(IISDefaults.AuthenticationScheme)
.AddJwtBearer(options => { /* Configure JWT options if needed */ });
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
2.获取当前用户信息:
- 在控制器中,您可以使用
ClaimsPrincipal来获取当前用户的信息。
[ApiController]
[Route("[controller]")]
public class UserController : ControllerBase
{
[HttpGet]
public IActionResult GetUserInfo()
{
var user = User;
var username = user.FindFirst(ClaimTypes.NameIdentifier)?.Value;
var domain = user.FindFirst(ClaimTypes.Name)?.Value;
return Ok(new { Username = username, Domain = domain });
}
}
3. 配置前端应用
1.确保前端应用能够处理身份验证:
- 确保前端应用能够处理身份验证,例如通过设置适当的CORS策略以避免跨域问题。
2.调用后端API获取用户信息:
- 使用Axios调用后端API以获取用户信息。
import axios from 'axios';
const getUserInfo = async () => {
try {
const response = await axios.get('/api/user');
console.log(response.data);
} catch (error) {
console.error(error);
}
};
getUserInfo();
-
使用
fetchAPI:在使用
fetch时,确保设置credentials选项为'include',以便包含身份验证凭据:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Get User Info</title>
</head>
<body>
<div id="result"></div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const apiUrl = '.../api/Redoc/GetUserInfo';
const resultDiv = document.getElementById('result');
fetch(apiUrl, { credentials: 'include' })
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => {
// 处理可能的 null 值
const username = data.username !== null ? data.username : 'N/A';
const domain = data.domain !== null ? data.domain : 'N/A';
resultDiv.innerHTML = `
<p>Username: ${username}</p>
<p>Domain: ${domain}</p>
`;
})
.catch(error => {
resultDiv.innerHTML = `<p>Error: ${error.message}</p>`;
console.error('Error:', error);
});
});
</script>
</body>
</html>
4. 测试配置
1.测试身份验证:
- 在浏览器中访问您的应用,确保Windows身份验证正常工作。
- 确保后端能够正确获取并返回用户信息。
通过以上步骤,您可以在IIS中部署前端应用并使用Windows身份验证获取域账户信息。确保所有配置都正确无误,以便应用能够正常运行。