2

FormsAuthentication.SetAuthCookie( "someUser"、false);を呼び出して、統合テスト内で認証しようとしています。
その後、許可された属性が適用されているため、WebAPIを呼び出す必要があり、許可されていない例外を受け取らないようにする必要があります。私はこのコードを使用して認証Cookieを作成しています:

var cookie = FormsAuthentication.GetAuthCookie(name, rememberMe);
    var ticket = FormsAuthentication.Decrypt(cookie.Value);

    var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration,
        ticket.IsPersistent, userData.ToJson(), ticket.CookiePath);
    var encTicket = FormsAuthentication.Encrypt(newTicket);

    /// Use existing cookie. Could create new one but would have to copy settings over...
    cookie.Value = encTicket;

次に、このCookieを新しいHttpClient内のHttpRequestMessageに追加し、統合テストで通常のリクエストとともに送信します。

その認証CookieをHttpRequestMessageに追加する方法がわかりませんか?

4

2 に答える 2

4

Cookieを操作するには、 WebRequestHandlerを。と一緒に使用する必要がありますHttpClient。例えば、

 var handler = new WebRequestHandler();
 var client = new HttpClient(handler);
 // use handler to configure request such as add cookies to send to server

CookieContainerプロパティは、Cookieコレクションへのアクセスを許可します。

別の注意点として、クライアントでFormsAuthenticationCookieを作成することが機能するかどうかは疑問です。クライアント/サーバーの両方で同じ暗号化キーが必要になります。最善のアプローチは、実際のWeb APIのログイン要求を再生することです。おそらく、ユーザー資格情報を使用してログインページにPOSTすることです。Fiddlerなどのツールを使用してブラウザで同じことを観察し、httpクライアント内で同じリクエストを作成します。

于 2012-11-30T09:58:03.783 に答える
0

ほぼ6年遅れていますが、それでも役立つ場合があります。これに基づくソリューション: https ://blogs.taiga.nl/martijn/2016/03/10/asp-net-web-api-owin-authenticated-integration-tests-without-authorization-server/

まず、Owin TestServerを作成するときに、DataProtectorを作成する必要があります。

    private readonly TestServer _testServer;
    public IDataProtector DataProtector { get; private set; }

    public Server(OwinStartup startupConfig)
    {
        _testServer = TestServer.Create(builder =>
        {
            DataProtector = builder.CreateDataProtector(
                typeof(CookieAuthenticationMiddleware).FullName, DefaultAuthenticationTypes.ApplicationCookie, "v1");

            startupConfig.Configuration(builder);
        });
    }

次に、次のようなCookieを生成します(前の手順で作成したDataProtectorを使用します)。

    public string GeterateCookie()
    {
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Role, "your-role"),
            new Claim(ClaimTypes.UserData, "user-data"),
            new Claim(ClaimTypes.Name, "your-name")
        };

        var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.Name, ClaimTypes.Role);

        var tdf = new TicketDataFormat(DataProtector);
        var ticket = new AuthenticationTicket(identity, new AuthenticationProperties {ExpiresUtc = DateTime.UtcNow.AddHours(1)});

        var protectedCookieValue = tdf.Protect(ticket);

        var cookie = new CookieHeaderValue("yourCookie", protectedCookieValue)
        {
            Path = "/",
            HttpOnly = true
        };

        return cookie.ToString();
    }

必ず必要なクレームを設定し、UseCookieAuthenticationメソッドに提供された設定に従ってClaimsIdentityを初期化し、正しいCookieNameを設定してください。

最後のステップは、CookieHeaderをリクエストに追加することです。

    public Task<HttpResponseMessage> RequestAsync(HttpRequestMessage request)
    {
        request.Headers.Add("cookie", GenerateCookie());
        return _client.SendAsync(request);
    }
于 2018-06-28T05:55:43.770 に答える