简体   繁体   English

如何在MVC4中包括基本的HTTP身份验证

[英]How to include a basic http authentication in MVC4

I am using the new oAuthWebSecurity functionality in MVC4 to do Facebook authentication for users of the site and it works great. 我正在MVC4中使用新的oAuthWebSecurity功能对网站的用户进行Facebook身份验证,并且效果很好。

However, what I would like to do is that for a specific controller only, enable basic HTTP authentication. 但是,我只想对特定的控制器启用基本的HTTP身份验证。

I have tried implementing a custom action filter (authenticationFilter) to intercept the call and do the basic authentication with custom code but the code never hits the overloads of the AuthorizationFilter . 我尝试实现一个自定义操作过滤器(authenticationFilter)来拦截该调用并使用自定义代码进行基本身份验证,但是该代码从未遇到AuthorizationFilter的重载。

Is there an easier way to implement this rather than creating a custom SimpleMembershipProvider ? 有没有比创建自定义SimpleMembershipProvider更简单的方法呢?

You can use [Authorize] filter is as below. 您可以使用以下[Authorize]过滤器。

public class BooksController : ApiController
{
    [Authorize]
    public IEnumerable<Book> Get()
    {
        var result = new List<Book>()
        {
            new Book()
            {
                Author = "John Fowles",
                Title = "The Magus",
                Description = "A major work of mounting tensions " +
                                "in which the human mind is the guinea-pig."
            },
            new Book()
            {
                Author = "Stanislaw Ulam",
                Title = "Adventures of a Mathematician",
                Description = "The autobiography of mathematician Stanislaw Ulam, " +
                                "one of the great scientific minds of the twentieth century."
            }
        };
        return result;
    }
}

For more information check Basic HTTP authentication 有关更多信息,请检查基本HTTP身份验证。

I hope this will help to you. 希望对您有帮助。

You can create custom AuthorizeAttribute to handle both authentication and authorization using basic authentication. 您可以创建自定义AuthorizeAttribute以使用基本身份验证来处理身份验证和授权。 This attribute works as a filter and will process the request before it gets to your controller action or Web API method. 此属性用作过滤器,将在请求进入控制器操作或Web API方法之前对其进行处理。 In the overridden OnAuthorize method you can grab the header information to perform authentication. 在重写的OnAuthorize方法中,您可以获取标头信息以执行身份验证。

If you are using ajax to make request to a controller or Web API method use basic authentication to pass the credentials for authorization. 如果您使用ajax向控制器或Web API方法发出请求,请使用基本身份验证来传递用于授权的凭据。 This puts the credentials in the header. 这会将凭证放在标头中。 To do this is pretty straight forward by using the beforeSend event handler of the JQuery ajax function. 通过使用JQuery ajax函数的beforeSend事件处理程序,可以很直接地做到这一点。 Use jquery.base64.js to encode the information being sent over. 使用jquery.base64.js对发送过来的信息进行编码。 Here is an example of how to do this. 这是如何执行此操作的示例。

    getAuthorizationHeader = function (username, password) {
      var authType;
      var up = $.base64.encode(username + ":" + password);
      authType = "Basic " + up;
    };
    return authType;
 };

    $.ajax({
        url: _url,
        data: _data,
        type: _type,
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization", getAuthorizationHeader(username, password));
        },
        success: ajaxSuccessHandler,
        error: ajaxErrHandler
    });

This encodes the username/password that is sent in the header. 这对在标题中发送的用户名/密码进行编码。 Note that this is not enough security to rely on just the encoding as it is easy to decode. 请注意,这仅靠编码是不够的,因为它很容易解码。 You still want to use HTTPS/SSL to make sure the information sent over the wire is secure. 您仍然想使用HTTPS / SSL来确保通过网络发送的信息是安全的。

On the server side you can make a custom AuthorizeAttribute that gets the credentials from the header, decodes them, and performs your authentication/authorization process. 在服务器端,您可以创建一个自定义AuthorizeAttribute ,以从标头中获取凭据,对凭据进行解码,然后执行身份验证/授权过程。 Note that there is aaa separate AuthorizeAttribute used by the Web API as opposed to the controller. 请注意,Web API使用了与控制器相对的一个单独的AuthorizeAttribute Be sure to use System.Web.Http.AuthorizeAttribute as your base class when creating your custom AuthorizeAttribute if you are using Web API. 如果使用Web API,则在创建自定义AuthorizeAttribute时,请确保使用System.Web.Http.AuthorizeAttribute作为基类。 They have different behaviors. 他们有不同的行为。 The one for the controller will want to redirect to the logon page whereas the one for the Web API returns an HTTP code indicating success or failure. 控制器的一个将要重定向到登录页面,而Web API的一个将返回指示成功或失败的HTTP代码。 I return an HTTP code of Forbidden if authorization fails to distinguish a failure due to authorization as opposed to authentication so the client can react accordingly. 如果授权未能区分由于授权而不是认证引起的失败,我将返回HTTP代码Forbidden,以便客户端可以做出相应反应。

Here is an example method for getting the credentials from the header that can be used in the custom AuthorizeAttribute . 这是从可在自定义AuthorizeAttribute中使用的标头获取凭证的示例方法。

    private bool GetUserNameAndPassword(HttpActionContext actionContext, out string username, out string password)
    {
        bool gotIt = false;
        username = string.Empty;
        password = string.Empty;
        IEnumerable<string> headerVals;
        if (actionContext.Request.Headers.TryGetValues("Authorization", out headerVals))
        {
            try
            {
                string authHeader = headerVals.FirstOrDefault();
                char[] delims = { ' ' };
                string[] authHeaderTokens = authHeader.Split(new char[] { ' ' });
                if (authHeaderTokens[0].Contains("Basic"))
                {
                    string decodedStr = SecurityHelper.DecodeFrom64(authHeaderTokens[1]);
                    string[] unpw = decodedStr.Split(new char[] { ':' });
                    username = unpw[0];
                    password = unpw[1];
                }
                gotIt = true;
            }
            catch { gotIt = false; }
        }

        return gotIt;
    }

And here is the code for decoding the header data that is used in this method. 这是用于解码此方法中使用的标头数据的代码。

    public static string DecodeFrom64(string encodedData)
    {

        byte[] encodedDataAsBytes

            = System.Convert.FromBase64String(encodedData);

        string returnValue =

           System.Text.Encoding.ASCII.GetString(encodedDataAsBytes);

        return returnValue;

    }

Once you have the username and password you can perform your authentication and authorization using the SimpleMembership provider. 有了用户名和密码后,就可以使用SimpleMembership提供程序执行身份验证和授权。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM