24

ASP.NET Web APIセルフホストオプションをWindows認証で使用しようとしています。これにより、ログオンしているユーザーを特定し、最終的にユーザーのIDに基づいてユーザーを承認または拒否できます。これが私のコンソールアプリケーションコードです:

using System;
using System.Web.Http;
using System.Web.Http.SelfHost;

namespace SelfHost
{
    class Program
    {
        static void Main(string[] args)
        {
            var config = new HttpSelfHostConfiguration("http://myComputerName:8080");
            config.UseWindowsAuthentication = true;

            config.Routes.MapHttpRoute(
                "API Default", "api/{controller}/{id}",
                new { id = RouteParameter.Optional });

            using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();

                Console.WriteLine("Press Enter to quit.");
                Console.ReadLine();
            }
        }
    }
}

コントローラは次のとおりです。

[Authorize]
public class HelloController : ApiController
{
    public string Get()
    {
        // This next line throws an null reference exception if the Authorize
        // attribute is commented out.
        string userName = Request.GetUserPrincipal().Identity.Name;
        return "Hello " + userName;
    }
}

編集-Authorize属性を追加しましたが、デバッガーはGetactionメソッド内のコードが呼び出されないことを示しています。次のHTMLが返されます。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META content="text/html; charset=windows-1252" http-equiv=Content-Type></HEAD>
<BODY></BODY></HTML>

Authorize属性がコメント化されている場合、 nullが生成さRequest.GetUserPrincipal().Identity.Nameれるため、null参照例外がスローされRequest.GetUserPrincipal()ます。

4

9 に答える 9

3

私はこれに少し遅れています。ただし、Owin を使用して自己ホストし、Windows 認証が必要な場合。スタートアップ クラスでは、以下を追加できます。

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        HttpListener listener = (HttpListener)app.Properties["System.Net.HttpListener"];
        listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication;
    }
}
于 2016-04-26T16:49:36.833 に答える
2

tpeczekの回答に似ていますが、HTTPS の使用を反映するように更新されています。tpeczekの回答は HTTPS では機能しません。これは、HTTPS での呼び出しがbase.OnConfigureBinding(httpBinding);変更を上書きするためです。httpBinding.Security.Mode = HttpBindingSecurityMode.TransportCredentialOnly;また、 HTTPSでは使用できません。

カスタム HttpSelfHostConfiguration を使用します。

public class NtlmSelfHostConfiguration : HttpSelfHostConfiguration
{
    public NtlmSelfHostConfiguration(string baseAddress)
        : base(baseAddress)
    { }

    public NtlmSelfHostConfiguration(Uri baseAddress)
        : base(baseAddress)
    { }

    protected override BindingParameterCollection OnConfigureBinding(
        HttpBinding httpBinding)
    {
        if (this.BaseAddress.Scheme == Uri.UriSchemeHttps)
        {
            var ret = base.OnConfigureBinding(httpBinding);
            httpBinding.Security.Transport.ClientCredentialType =
                HttpClientCredentialType.Ntlm;
            return ret;
        }

        httpBinding.Security.Mode = HttpBindingSecurityMode.TransportCredentialOnly;
        httpBinding.Security.Transport.ClientCredentialType = 
            HttpClientCredentialType.Ntlm;
        return base.OnConfigureBinding(httpBinding);
    }
}

次に、次のことができます

var config = new NtlmSelfHostConfiguration("http://myComputerName:8080");

また

var config = new NtlmSelfHostConfiguration("https://myComputerName:8443");

渡す構成を取得するnew HttpSelfHostServer(config)

于 2014-12-12T23:53:59.573 に答える
1

認証の使用方法を説明する短いビデオへのリンクを次に示します。

http://www.asp.net/web-api/videos/getting-started/authorization

基本的に、クラスで [Authorize] 属性を使用し、エラーをキャッチして HTTP 401 応答を返し、クライアントにそれを検出させてログイン ページに移動します。

于 2012-03-07T05:35:55.170 に答える
1

[Authorize]コントローラーに属性を入れてみましたか?

[Authorize]
public class HelloController : ApiController
于 2012-03-05T20:51:43.937 に答える
1

追加するために、tpeczek のソリューションを使用していて、HttpClient も使用している場合は、これを行う必要がある場合があります。

        var handler = new HttpClientHandler();
        handler.UseDefaultCredentials = true;
        _httpClient = new HttpClient(handler);
于 2013-10-16T19:49:27.220 に答える
0

トークンを使用した基本認証について、必要な人のための関連回答

いくつかのヘルプ、情報、回答、および実際の Web API 用に作成した自己認証システムをマージして、最終的にこれにロールと属性タグを使用できるようになりました。ヘッダー内の Authorization タグ用に作成されています。

サーバー呼び出し:

 var config = new HttpSelfHostConfiguration("http://localhost:8080");
            config.UserNamePasswordValidator = new PHVValidator();
            config.Routes.MapHttpRoute(
                "API Default", "{controller}/{id}",
                new { id = RouteParameter.Optional });

            using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new DominusForm());
            }

認証方法: (ex. のみのハードコード、どこからでもユーザー、パス、ロールを選択)

    public class PHVValidator : System.IdentityModel.Selectors.UserNamePasswordValidator
    {
        public override void Validate(string userName, string password)
        {
            if (userName == "admin" && password == "123")
            {
                string[] rolarray = new string[] { "admin" };
               IPrincipal principal = new GenericPrincipal(new GenericIdentity(userName), rolarray);
                Thread.CurrentPrincipal = principal;
            }
        }
    }

方法:

[Authorize(Roles = "admin")]
public HttpResponseMessage Get()
{
     do things
}
于 2017-07-25T17:51:19.733 に答える