3

私はsqlserverバックエンドを備えたasp.net-mvcサイトを持っており、ログインなどにmembershipproviderを使用しています.

次の場合に今日実行できるので、毎日または毎週実行したい自動化されたものがいくつかあります。

  1. ログインする
  2. 呼び出し URL

URLが

www.mysite.com/MyController/RunCleanupScript

RunCleanupScript のコードを Web サイト外のスタンドアロン スクリプトに分割することを提案する人もいると思いますが、手動ログインに相当するものを自動化し、この URL を入力してこのスクリプトを呼び出す解決策があるかどうかを確認したかったのです。

4

7 に答える 7

4

Phil Haak は、あなたに役立つかもしれない解決策についての投稿をしています - 彼はまた、関連する危険性について警告しています. この方法を使用して、クリーンアップ タスクをスケジュールできます。クリーンアップ コードをコントローラーの外に移動した場合、ログインは必要ありません。外部から呼び出すことはできません。それでもログインして強制的にクリーンアップできるようにする必要がある場合は、クリーンアップ コードをコントローラーから移動することをお勧めします。セキュリティで保護されたアクションとスケジューラ コードの両方が、クリーンアップ コードを呼び出します。

もう 1 つのオプションは、アクションを実行し、必要な資格情報を構成ファイルに保存する Windows サービスを作成することです。

于 2011-10-21T12:03:17.703 に答える
2

フォーム認証と、Cookieを取得するためにWebページを呼び出すいくつかのスクリプトは、要件に対して最も安定した保守可能なアプローチではない場合があります。

スクリプトからのユーザー名とパスワードの受け渡しを容易にする基本認証をサポートできます。asp.net mvcで基本認証を実装する方法の例については、このブログ投稿を参照してください。

于 2011-10-20T05:44:24.707 に答える
2

2 つの HTTP 要求を実行するコンソール アプリケーションを作成できます。1 つはログイン、2 番目は保護されたリソースをフェッチします。

using System;
using System.Collections.Specialized;
using System.Net;

public class WebClientEx: WebClient
{
    private readonly CookieContainer _cookieContainer = new CookieContainer();

    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address);
        ((HttpWebRequest)request).CookieContainer = _cookieContainer;
        return request;
    }
}

class Program
{
    static void Main()
    {
        using (var client = new WebClientEx())
        {
            var values = new NameValueCollection
            {
                { "username", "user" },
                { "password", "pwd" },
            };
            // Login
            client.UploadValues("http://example.com/account/logon", values);

            // Fetch the protected resource
            var result = client.DownloadString("http://example.com/home/foo");
            Console.WriteLine(result);
        }
    }
}
于 2011-10-20T06:02:12.427 に答える
1

このコードは FormsAuthentication サイトにログインし、AUTH Cookie を使用してサイト上の他の URL にアクセスします...

string appURL = "https://.../LogOn";

// UserName and Password should match the names of the inputs on your form
string strPostData = String.Format("UserName={0}&Password={1}", "login", "pass");

Cookie authCookie;
CookieContainer cookieJar = new CookieContainer();

// Prepare post to the login form
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(appURL);

req.Method = "POST";
req.ContentLength = strPostData.Length;
req.ContentType = "application/x-www-form-urlencoded";
req.CookieContainer = cookieJar;
req.AutomaticDecompression = DecompressionMethods.GZip
                             | DecompressionMethods.Deflate;

// Proxy - Optional
// req.Proxy.Credentials = CredentialCache.DefaultCredentials;

// Post to the login form.
StreamWriter swRequestWriter = new StreamWriter(req.GetRequestStream());
swRequestWriter.Write(strPostData);
swRequestWriter.Close();

// Get the response.
HttpWebResponse hwrWebResponse = (HttpWebResponse)req.GetResponse();


// Store the required AUTH cookie
authCookie = cookieJar.GetCookies(new Uri("... your cookie uri ..."))[".ASPXAUTH"];

これで、AUTH Cookie を使用してサイトの他の URL にアクセスできます。

HttpWebRequest req = (HttpWebRequest)WebRequest.Create("... url ...");

req.CookieContainer.Add(new System.Net.Cookie(authCookie.Name,
                          authCookie.Value,
                          authCookie.Path, "localhost"));

HttpWebResponse resp = (HttpWebResponse) req.GetResponse();
于 2011-10-22T07:18:03.580 に答える
0

PowerShell はあなたにとって良い選択肢かもしれません。フォームの値をログオン ページに送信し、応答 Cookie を使用して管理ページへの 2 回目の呼び出しを行う方法を示すサンプルを次に示します。

このサンプルの多くは、この投稿から借用したことに注意してください。

$LogonUrl = "http://yoursite.com/Account/LogOn"
$UserName = "AdminUser"
$Password = "pass@word1"
$AdminUrl = "http://yoursite.com/MyController/RunCleanupScript"

$cookies = New-Object System.Net.CookieContainer
$formData = "UserName=" + $UserName + "&Password=" + $Password

[net.httpWebRequest] $web1 = [net.webRequest]::create($LogonUrl)
$web1.method = "POST"
$web1.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
$web1.Headers.Add("Accept-Language: en-US")
$web1.Headers.Add("Accept-Encoding: gzip,deflate")
$web1.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7")
$web1.AllowAutoRedirect = $false
$web1.ContentType = "application/x-www-form-urlencoded"
$buffer = [text.encoding]::ascii.getbytes($formData)
$web1.ContentLength = $buffer.length
$web1.TimeOut = 50000
$web1.KeepAlive = $true
$web1.Headers.Add("Keep-Alive: 300");
$web1.CookieContainer = $CookieContainer

$reqStrm = $web1.getRequestStream()
$reqStrm.write($buffer, 0, $buffer.length)
$reqStrm.flush()
$reqStrm.close()
[net.httpWebResponse] $response = $web1.getResponse()

$respStrm = $response.getResponseStream()
$reader = new-object IO.StreamReader($respStrm)
$result = $reader.ReadToEnd()
$response.close()

$web2 = new-object net.webclient
$web2.Headers.add("Cookie", $response.Headers["Set-Cookie"])
$result = $web2.DownloadString("$AdminUrl")

Write-Output $result

これは、Windows コンソール アプリにも簡単に変換できます。いずれにせよ、タスク スケジューラを使用して簡単にスケジュールを設定できます。

お役に立てれば。

于 2011-10-20T00:23:13.603 に答える
0

WatiNSeleniumを試してみませんか? ログイン手順を非常に簡単に設定してから、他の RunCleanupScript ページが正しく機能しているかどうかをテストできます。

WatiN のメイン ページの例:

[Test] 
public void SearchForWatiNOnGoogle()
{
  using (var browser = new IE("http://www.google.com"))
  {
    browser.TextField(Find.ByName("q")).TypeText("WatiN");
    browser.Button(Find.ByName("btnG")).Click();

    Assert.IsTrue(browser.ContainsText("WatiN"));
  }
}

次に、次のようなものを使用できます。

[Test] 
public void TestRunCleanupScript()
{
  using (var browser = new IE("www.mysite.com/MyController/RunCleanupScript"))
  {
    DoLogin(browser)
    //navigate to cleanupscript page      
    //your assert
  }
}

public void DoLogin(browser)
{
  //navigate to login
  //type username and password and hit button
}
于 2011-10-20T10:31:21.147 に答える
0

私は現在、本番環境でこれを行っています。私の場合、通常の RSS リーダーがサイト上の RSS フィードに安全にアクセスできるようにするために MADAM が既にインストールされていたので、ソリューションは非常に簡単でした。

これを行う秘訣は、外部プロセスを使用して自動的に呼び出したいページの基本認証を有効にすることです。これにより、サイトに自動的にアクセスするための膨大な数の方法が可能になります。たとえば、この VBScript ファイルはメンテナンス URL を呼び出し、サーバーからの応答が正確かどうかをチェックしますSUCCESS

Option Explicit

Dim result
result = PerformMaintenance("http://www.mysite.com/MyController/RunCleanupScript")
WScript.Quit(result)

Function PerformMaintenance(URL)

  Dim objRequest

  Set objRequest = CreateObject("Microsoft.XmlHttp")

  'I use a POST request because strictly speaking a GET shouldn't change anything on the server.
  objRequest.open "POST", URL, false, "LimitedDaemonUser", "SecretDaemonPassword"
  objRequest.Send

  if (objRequest.ResponseText = "SUCCESS") Then
    PerformMaintenance = 0
  Else
    PerformMaintenance = 1
  End If

  set objRequest = Nothing

End Function

基本認証は簡単に機能します。MADAMをプロジェクトに含めて、Web.config で構成するだけです。

これらの Web.config セクション/パラメーター (IIS6) を追加すると、標準の MembershipProvider を使用する場合、サンプル リクエストが機能するはずです。MyNamespace.MembershipUserSecurityAuthority実際のクラスへの参照に変更するだけです。のソース コードMembershipUserSecurityAuthorityは、MADAM のデモ Web アプリケーションのApp_Codeフォルダーに含まれています。

<configuration>
<configSections>
    <sectionGroup name="madam">
      <section name="userSecurityAuthority" type="System.Configuration.SingleTagSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      <section name="formsAuthenticationDisposition" type="Madam.FormsAuthenticationDispositionSectionHandler, Madam" />
    </sectionGroup>
</configSections>
  <madam>
    <userSecurityAuthority realm="MyRealm" provider="MyNamespace.MembershipUserSecurityAuthority, MyNamespace" />
    <formsAuthenticationDisposition>
      <discriminators all="false">
        <discriminator inputExpression="Request.AppRelativeCurrentExecutionFilePath" pattern="~/MyController/RunCleanupScript$" type="Madam.RegexDiscriminator, Madam" />
        </discriminators>
    </formsAuthenticationDisposition>
  </madam>
  <system.web>
    <httpModules>
      <add name="FormsAuthenticationDisposition" type="Madam.FormsAuthenticationDispositionModule, Madam" />
      <add name="AuthenticationModule" type="Madam.BasicAuthenticationModule, Madam" />
    </httpModules>
  </system.web>
</configuration>
于 2011-10-23T20:12:43.997 に答える