带有 OWIN 的 WebApi 2 - 授权挑战不会重定向到登录

Posted

技术标签:

【中文标题】带有 OWIN 的 WebApi 2 - 授权挑战不会重定向到登录【英文标题】:WebApi 2 with OWIN - Authorization Challenge does not redirect to Log In 【发布时间】:2018-06-22 13:23:06 【问题描述】:

我正在尝试利用 OWIN 和 OpenIdConnect 身份验证来登录 Azure Active Directory。我的应用程序是使用 WebApi 2 的 ASP .NET。此时前端只是简单的 html/javascript。在本地运行我的应用程序时,我在控制器上调用 WebApi(控制器和任何 API 都没有 [Authorize] 过滤器),然后该 API 使用当前的 OWIN 上下文来挑战身份验证。此挑战按预期失败,因为我没有登录并继续调用“https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=...”,这也是预期的。请求返回 200 状态,响应包含 Microsoft 登录页面的 HTML。但是,我的 Web 应用程序不会重定向到该登录页面,并且控制台会显示 CORS 错误:

无法加载https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=[removed]&redirect_uri=http%3a%2f%2flocalhost%3a20776%2f&response_mode=form_post&response_type=code+id_token&scope=openid+email+profile+offline_access+User.Read+Mail.Send+Files.ReadWrite&state=OpenIdConnect.AuthenticationProperties[removed]:

对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问 Origin 'http://localhost:20776'。

我通过浏览器扩展程序强行解决了 CORS 问题,但即便如此,它也没有重定向到标志页面。相反,响应包含之前登录页面的来源。我已经概述了我已采取的步骤以及我在下面使用的代码。我错过了一步吗?

我发现的大多数文档和示例都利用了 ASP.NET MVC。我的大部分实现都基于此处找到的 MVC 示例:https://github.com/Azure-Samples/active-directory-dotnet-webapp-groupclaims

该示例在本地运行良好,我能够使用我的 AAD 凭据登录并成功调用 MS Graph API。

至于 CORS 问题,我在 MVC 示例中没有看到这一点。为什么这个 CORS 问题出现在我当前的设置中,我该如何解决?我希望 OWIN 中间件能够解决这个问题。在控制器上使用 EnableCors 过滤器没有帮助,在 IAppBuilder 上启用 CORS 也没有帮助。

我期望的网络请求是(基于 OWIN MCV 示例):

//Call to sign in which initiates the challenge
Request URL:http://localhost:55065/Account/SignIn
Request Method:GET
Status Code:302 Found
Remote Address:[::1]:55065
Referrer Policy:no-referrer-when-downgrade

//Call to perform the challenge.  Should redirect to MS login after this
Request 
URL:https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=[truncated]
Request Method:GET
Status Code:200 OK
Remote Address:104.42.72.20:443
Referrer Policy:no-referrer-when-downgrade

我在 WebApi 项目中实际看到的网络请求是:

Request URL:http://localhost:13291/api/v1/tools/user/signin
Request Method:GET
Status Code:302 Found
Remote Address:[::1]:13291
Referrer Policy:no-referrer-when-downgrade

Request URL:http://localhost:13291/api/v1/tools/user/signin
Request Method:POST
Status Code:302 Found
Remote Address:[::1]:13291
Referrer Policy:no-referrer-when-downgrade

Request URL:https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=[truncated]
Request Method:OPTIONS
Status Code:200 OK
Remote Address:104.210.48.14:443
Referrer Policy:no-referrer-when-downgrade

Request URL:https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=[truncated]
Request Method:GET
Status Code:200 OK
Remote Address:104.210.48.14:443
Referrer Policy:no-referrer-when-downgrade

以下是我的设置摘要以及相关代码:

通过 Azure AD 注册了一个新应用程序,回复 URL 为 http://localhost:13291,以匹配我在本地运行的应用程序。 我使用与 OpenIdConnectionAuthenticationOptions 的 RedirectUri 相同的 URL 我使用注册应用的 AppID 作为 OpenIdConnectionAuthenticationOptions 的 ClientID React 正在使用 JQuery $.post 唯一启用 CORS 的地方是在 OWIN 启动类中的 IAppBuilder 之外。

代码摘录 为简洁起见,我删除了命名空间定义和一些类定义。下面的代码来自我创建的一个新的最小示例,用于在我正在处理的大型 Web 应用程序之外重现问题。前端只是一个简单的 JQuery 调用。我想提供对解决方案的访问权限,但它目前包含我的 AppSecret,我认为它甚至需要尝试重现它。

WebApiConfig.cs

public static HttpConfiguration Register()

    var config = new HttpConfiguration();
    config.MapHttpAttributeRoutes();
    return config;

Startup.cs

[assembly: OwinStartup(typeof(Startup))]

public partial class Startup

    public void Configuration(IAppBuilder app)
    
        ConfigureAuth(app);
    

Startup.Auth.cs

public partial class Startup

    //...
    //Obtain various application settings
    //...

    public void ConfigureAuth(IAppBuilder app)
    
        app.UseCors(CorsOptions.AllowAll);  
        app.SetDefaultSignInAsAuthenticationType( CookieAuthenticationDefaults.AuthenticationType);
        app.UseCookieAuthentication(new CookieAuthenticationOptions());

        app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
        
            ClientId = appId,
            Authority = "https://login.microsoftonline.com/common/v2.0",
            PostLogoutRedirectUri = redirectUri,
            RedirectUri = redirectUri,  //http://localhost:13291
            TokenValidationParameters = ...,
            Notifications = ...,
            AuthenticationFailed = ...
        

        app.UseWebApi(WebApiConfig.Register());
    

FooController.cs

public class FooController : ApiController

    [Route("api/v1/tools/user/signin")]
    [HttpPost]
    public HttpResponseMessage SignIn()
    
        if (HttpContext.Current.User == null || HttpContext.Current.User.Identity.IsAuthenticated == false)
        
            var properties = new AuthenticationProperties() RedirectUri = "/";
            Request.GetOwinContext().Authentication
                   .Challenge(properties, OpenIdConnectAuthenticationDefaults.AuthenticationType);

            return Request.CreateResponse(HttpStatusCode.Unauthorized);
        

        return Request.CreateResponse(HttpStatusCode.OK);
    

index.html

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script type="text/javascript">
        function signIn() 
            $.post("/api/v1/tools/user/signin", (r) => 
            ).fail((e) => 
                console.log(e);
            );
        
    </script>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <input id="signIn" type="button" value="SignIn" onclick="signIn();" />
</body>
</html>

【问题讨论】:

与 CORS 相同的问题,使用 web api 2 和 angular 4,但是当我丢失 cookie 时间到期时触发的 CORS。我正在尝试访问 microsoft Graph API 以请求信息。这是错误:无法加载login.microsoftonline.com/common/oauth2/v2.0/…:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问 Origin 'localhost:44300'。 【参考方案1】:

https://weblog.west-wind.com/posts/2016/Sep/26/ASPNET-Core-and-CORS-Gotchas 看看这个,它帮助我在我的 web api 上处理来自 angular 的跨域请求

【讨论】:

谢谢,我看了一下那个帖子,但无法解决。我认为这是 WebApi 和 OWIN 之间的配置问题。我认为 OWIN 中间件应该在发出身份验证请求和重定向时处理 CORS,但在我的情况下不会发生这种情况。

以上是关于带有 OWIN 的 WebApi 2 - 授权挑战不会重定向到登录的主要内容,如果未能解决你的问题,请参考以下文章

在WebApi中基于Owin OAuth使用授权发放Token

授权角色 WebAPI oauth owin

授权角色 WebAPI oauth owin

Owin OAuth 2.0密码授权流程

如何从 OAuth 客户端凭据开始使用 OWIN Oauth 保护 WebApi?

“错误:” “Unsupported_grant_type” 使用 OAuth 2.0,Owin。密码授予和授权授予