Angular 7部署S3桶后Azure AD登录重定向循环问题求助
问题描述
基于微软MSAL Angular的Angular7示例项目,修改app.component.ts的login方法,移除IE判断逻辑,仅使用重定向登录:
login() { // const isIE = window.navigator.userAgent.indexOf('MSIE ') > -1 || window.navigator.userAgent.indexOf('Trident/') > -1; // if (isIE) { this.authService.loginRedirect(); // } else { // this.authService.loginPopup(); // } }
将构建后的应用部署到S3桶后,点击登录跳转至Azure AD完成认证,回调回到domain.com/index.html#id_token=eyjsjsns....时出现持续重定向循环,无法完成登录。
解决方法
- 配置S3静态网站重定向规则:S3默认不支持Angular哈希路由的回调处理,需添加404重定向规则,将所有请求导向
index.html并保留哈希参数。在S3控制台的「静态网站托管」中添加以下规则:<RoutingRules> <RoutingRule> <Condition> <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals> </Condition> <Redirect> <HostName>domain.com</HostName> <ReplaceKeyPrefixWith>#/</ReplaceKeyPrefixWith> <HttpRedirectCode>200</HttpRedirectCode> </Redirect> </RoutingRule> </RoutingRules> - 校验MSAL的
redirectUri配置:确保app.module.ts中MSAL配置的redirectUri与Azure AD应用注册的重定向URI完全一致,必须包含index.html(例如https://domain.com/index.html),不能仅填写域名根路径。 - 启用Angular哈希路由:MSAL依赖哈希路由传递token,在
AppRoutingModule的路由配置中开启哈希模式:RouterModule.forRoot(routes, { useHash: true }) - 检查S3桶CORS配置:若存在跨域限制会导致token处理失败,配置CORS规则允许必要的请求:
<CORSConfiguration> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration> - 避免重复触发登录逻辑:检查
app.component.ts的初始化代码,确保仅在未检测到登录账户时才触发登录,防止循环:ngOnInit() { this.authService.handleRedirectCallback((error, response) => { // 处理回调结果,比如更新用户状态 }); const account = this.authService.getAccount(); if (!account) { // 仅在无登录账户时执行登录逻辑 // this.authService.loginRedirect(); } }
内容的提问来源于stack exchange,提问作者siva sankar
相关产品推荐
相关产品推荐

