与成员资格提供ASP.NET MVC 4的Web API认证 [英] ASP.NET MVC 4 Web API Authentication with Membership Provider

查看:150
本文介绍了与成员资格提供ASP.NET MVC 4的Web API认证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Web API的ASP.NET MVC 4项目。在控制器我已经设置了类需要使用[授权]属性的授权。为了验证我使用ASP.NET成员提供程序,并已我的web.config设置为使用表格认证。这里是我坚持:

I have an ASP.NET MVC 4 Project using the Web API. On the controller I have set the class to require authorization using the [Authorize] attribute. For Authentication I am using the ASP.NET Membership Provider and have my Web.Config set to use "Forms" Authentication. Here is where I am stuck:

一切是伟大的工作,直到,我与测试API做了点,我想保护与[授权]控制器属性,所以我可以在我的成员资格提供启动针对用户的测试认证。所以,我火了小提琴手,使同一个呼叫加入授权:以用户名以及基本属性:密码从我的成员提供像这样:

Everything is working great up until the point that I am done with testing the API and I want to secure the controller with the [Authorize] attribute so I can start testing authentication against users in my Membership Provider. So I fire up Fiddler and make the same call adding the Authorization:Basic attribute along with a username:password from my membership provider like so:

我得到的回应是401未授权和验证我得到的没有WWW验证标题为present。然后,我意识到,API是寻找一个SHA1 EN codeD密钥。所以,我火了从搜索的SHA1发电机,并获得了用户名的哈希:密码,并更新我的请求头,像这样:

The response I get is 401 unauthorized and under "Auth" I get "No WWW-Authenticate Header is present." Then I realize that the API is looking for an SHA1 encoded key. So I fire up an SHA1 generator from a search and get a hash for my username:password and update my Request Header like so:

这也不行,我也得到了相同的结果。此外,我显然需要某种形式的共享密钥与服务器使用脱code我的用户名/密码。

This does not work either and I get the same results. Also I obviously need some sort of "shared secret key" to use with the server to decode my username/password.

所以我的问题:


  1. 如何从服务器获取这个键(或者在这种情况下,虚拟IIS流失VS 2012)。

  2. 如何使用这个用户名使用/密码从ASP.NET成员资格提供程序,以使提琴手验证的调用。

  3. 如何将我在客户端应用程序也作出了同样的调用(C#WPF应用程序),使用此功能。

  4. 当我的HTTP调用SSL结合这是最佳实践的研究?如果不是有什么?

在此先感谢!

推荐答案

您可以使用基本身份验证使用SSL。在服务器端,我们可以写一个自定义的委托处理程序将通过查询我们注册的memebership供应商验证凭据,如果有效,检索角色和设定现任校长:

You could use basic authentication with SSL. On the server side we could write a custom delegating handler which will verify the credentials by querying the memebership provider that we registered, and if valid, retrieve the roles and set the current principal:

public class BasicAuthenticationMessageHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var authHeader = request.Headers.Authorization;

        if (authHeader == null)
        {
            return base.SendAsync(request, cancellationToken);
        }

        if (authHeader.Scheme != "Basic")
        {
            return base.SendAsync(request, cancellationToken);
        }

        var encodedUserPass = authHeader.Parameter.Trim();
        var userPass = Encoding.ASCII.GetString(Convert.FromBase64String(encodedUserPass));
        var parts = userPass.Split(":".ToCharArray());
        var username = parts[0];
        var password = parts[1];

        if (!Membership.ValidateUser(username, password))
        {
            return base.SendAsync(request, cancellationToken);
        }

        var identity = new GenericIdentity(username, "Basic");
        string[] roles = Roles.Provider.GetRolesForUser(username);
        var principal = new GenericPrincipal(identity, roles);
        Thread.CurrentPrincipal = principal;
        if (HttpContext.Current != null)
        {
            HttpContext.Current.User = principal;
        }

        return base.SendAsync(request, cancellationToken);
    }
}

我们再注册此处理在的Application_Start

GlobalConfiguration.Configuration.MessageHandlers.Add(
    new BasicAuthenticationMessageHandler()
);

现在,我们可以有一个API控制器将与[授权]装饰属性,以确保只有合法的用户才能访问它的动作:

Now we could have an Api controller that will be decorated with the [Authorize] attribute to ensure that only authenticated users can access its actions:

[Authorize]
public class ValuesController : ApiController
{
    public string Get()
    {
        return string.Format("Hello {0}", User.Identity.Name);
    }
}

好了,现在让我们来看看一个样本客户端:

Alright, now let's look at a sample client:

using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

class Program
{
    static void Main()
    {
        // since for testing purposes I am using IIS Express
        // with an invalid SSL certificate I need to desactivate
        // the check for this certificate.
        ServicePointManager.ServerCertificateValidationCallback += 
            (sender, certificate, chain, sslPolicyErrors) => true;

        using (var client = new HttpClient())
        {
            var buffer = Encoding.ASCII.GetBytes("john:secret");
            var authHeader = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(buffer));
            client.DefaultRequestHeaders.Authorization = authHeader;
            var task = client.GetAsync("https://localhost:44300/api/values");
            if (task.Result.StatusCode == HttpStatusCode.Unauthorized)
            {
                Console.WriteLine("wrong credentials");
            }
            else
            {
                task.Result.EnsureSuccessStatusCode();
                Console.WriteLine(task.Result.Content.ReadAsAsync<string>().Result);
            }
        }
    }
}

这篇关于与成员资格提供ASP.NET MVC 4的Web API认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆