.net MVC4, framework4.5 框架使用aad登录 遇到的坑
.net MVC4, framework4.5 框架使用aad登录 遇到的坑
先上官方文档, 我也是根据官方文档来做踩得坑!
https://learn.microsoft.com/zh-cn/azure/active-directory/develop/web-app-quickstart?pivots=devlang-aspnet&tabs=windows
框架上我的项目一开始是 framework4.0 升到4.5的 因为最低支持4.5版本
1. 先安装依赖包
Install-Package Microsoft.Owin.Security.OpenIdConnect
Install-Package Microsoft.Owin.Security.Cookies
Install-Package Microsoft.Owin.Host.SystemWeb
2. 设置aad 重定向
没有应用的话新注册
进入应用, 选择身份验证 > 添加url > 令牌选择 ID令牌 > 项目类型根据项目需要选择 > 保存
3. 配置 Web.config
参数官方文档有详细说明
4. 修改代码
4.1 配置 startup启动类
先添加类
然后把官方的代码复制进去就可以了
启动项目
登录的方法和注销可以直接用官方给的
public void SignIn()
{
if (!Request.IsAuthenticated)
{
HttpContext.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties{ RedirectUri = "/" },
OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
}
//注销
HttpContext.GetOwinContext().Authentication.SignOut(
OpenIdConnectAuthenticationDefaults.AuthenticationType,
CookieAuthenticationDefaults.AuthenticationType);
这时候就可以启动你的项目了
坑1
启动点击aad登录这个时候就遇到了一个框架的坑 , 点击跳转不到aad的登录页面,强制跳转到这个路径: Account/Login , 后查资料看到这个: https://www.cnblogs.com/amywechat/p/4885483.html
要在web.config加下配置
<add key="enableSimpleMembership" value="false" />
坑2
现在就能跳转到aad的登录页面了 , 完成登录回调后我又遇到一个报错: IDX21323
DX21323: RequireNonce is ‘[PII is hidden]’. OpenIdConnectProtocolValidationContext.Nonce was null, OpenIdConnectProtocol.ValidatedIdToken.Payload.Nonce was not null. The nonce cannot be validated. If you don’t need to check the nonce, set OpenIdConnectProtocolValidator.RequireNonce to ‘false’. Note if a ‘nonce’ is found it will be evaluated.
解决方案我 是把http访问改为https 就可以了
坑3
成功跳转后, 我发现我系统并没有登录成功, 检查发现已接收到token 但是request的 IsAuthenticated 状态没有改变
解决方案 : 在startup.cs 添加一个配置
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
CookieManager = new SystemWebCookieManager()
});
这就可以解决了
坑4
因为我的项目的账号类型限制只能是仅我的组织, 所以 参数 Tenant 改为目录租户ID, 控制台也要修改账号类型, 一切修改好了 登录测试 报错:
解决方案, 在startup.cs 添加这段代码
IdentityModelEventSource.ShowPII = true;
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12
| SecurityProtocolType.Ssl3;
到这项目就基本可以使用aad登录了 , 也可以根据需求使用联合登录 先跳aad登录 再跳 ADFS登录, 这块代码上不用调整了, 在AAD上配置好就可以了!