我正在尝试创建一个基于MVC的站点,通过WebApi向本地页面和外部客户端提供一些服务,因此要求JSONP避免相同的源策略错误。问题是该网站正在使用基本身份验证,正如我从其他帖子中了解到的,这里无法使用JSONP。我尝试注入用户:按照帖子How do I make a JSONP call with JQuery with Basic Authentication?中的建议传入URL,但这不起作用,服务器返回未经授权的代码。此外,我尝试在没有注入的情况下拨打电话,因为我可以在浏览器中输入用户名和密码:浏览器按要求请求我提供凭据,但由于某种原因他们被拒绝,再次结束未经授权的代码。然而凭据是可以的,因为我可以通过成功运行来自同一域的完全相同的代码来确认。谁能告诉我我的代码有什么问题?
我的MVC WebApi控制器操作如下:
[BasicAuthorize(Roles = "administrator,customer,trial")]
public class TextApiController : ApiController
{
// ...
public SomeResult Get([FromUri] SomeParams p)
{
// some processing which returns a SomeResult object
//...
}
}
其中BasicAuthorize属性是我从http://kevin-junghans.blogspot.it/2013/02/mixing-forms-authentication-basic.html修改的类,如下所示:
[AttributeUsageAttribute(AttributeTargets.Class |
AttributeTargets.Method, Inherited = true,
AllowMultiple = true)]
public sealed class BasicAuthorizeAttribute : AuthorizeAttribute
{
static private string DecodeFrom64(string sEncodedData)
{
byte[] encodedDataAsBytes = Convert.FromBase64String(sEncodedData);
return Encoding.ASCII.GetString(encodedDataAsBytes);
}
static private bool GetUserNameAndPassword(HttpActionContext context,
out string sUserName,
out string sPassword,
out bool bCookieAuthorization)
{
bCookieAuthorization = false;
bool bSuccess = false;
sUserName = sPassword = "";
IEnumerable<string> headerVals;
if (context.Request.Headers.TryGetValues("Authorization", out headerVals))
{
try
{
string sAuthHeader = headerVals.First();
string[] authHeaderTokens = sAuthHeader.Split();
if (authHeaderTokens[0].Contains("Basic"))
{
string sDecoded = DecodeFrom64(authHeaderTokens[1]);
string[] aPairMembers = sDecoded.Split(new[] { ':' });
sUserName = aPairMembers[0];
sPassword = aPairMembers[1];
}
else
{
if (authHeaderTokens.Length > 1)
sUserName = DecodeFrom64(authHeaderTokens[1]);
bCookieAuthorization = true;
}
bSuccess = true;
}
catch
{
bSuccess = false;
}
}
return bSuccess;
}
static private bool Authenticate(HttpActionContext actionContext,
out string sUserName)
{
bool bIsAuthenticated = false;
string sPassword;
bool bCookieAuthorization;
if (GetUserNameAndPassword(actionContext,
out sUserName, out sPassword, out bCookieAuthorization))
{
// if the header tells us we're using Basic auth then log the user in
if (!bCookieAuthorization)
{
if (WebSecurity.Login(sUserName, sPassword, true))
bIsAuthenticated = true;
else
WebSecurity.Logout();
}
// else get authentication from web security
else
{
if (WebSecurity.IsAuthenticated) bIsAuthenticated = true;
sUserName = WebSecurity.CurrentUserName;
}
}
else actionContext.Response =
new HttpResponseMessage(HttpStatusCode.BadRequest);
return bIsAuthenticated;
}
private bool IsAuthorized(string sUserName)
{
SimpleRoleProvider roles =
(SimpleRoleProvider)System.Web.Security.Roles.Provider;
string[] aRoles = Roles.Split(new[] {','});
return (aRoles.Any(sRole => roles.IsUserInRole(sUserName, sRole)));
}
public override void OnAuthorization(HttpActionContext actionContext)
{
string sUserName;
if (Authenticate(actionContext, out sUserName))
{
if (!IsAuthorized(sUserName))
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
}
else
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
}
}
}
我的客户端代码是一个带有一些Javascript(使用jQuery)的简单HTML页面,如:
...
<form>
<fieldset>
<legend></legend>
<ol>
<li>
input text
<input type="text" id="input"/>
</li>
<li>
username
<input type="text" id="user"/>
</li>
<li>
password
<input type="password" id="password"/>
</li>
<li><a href="#" id="apip">API: JSONP</a></li>
</ol>
</fieldset>
</form>
<div id="result"></div>
<script>
function getAuthorizationHeader(username, password) {
"use strict";
var authType;
if (password == "") {
authType = "Cookie " + $.base64.encode(username);
}
else {
var up = $.base64.encode(username + ":" + password);
authType = "Basic " + up;
};
return authType;
};
function ajaxSuccessHandler(data) {
"use strict";
$("#result").text(data);
};
function ajaxErrHandler(jqXHR, textStatus, errorThrown) {
"use strict";
$("#result").text(errorThrown + " : " + textStatus);
}
$(function () {
"use strict";
$("#apip").click(function () {
"use strict";
var text = $("#input").val();
$.ajax({
url: "https://somesiteurl.com/api/wordapi?Text=" + encodeURIComponent(text),
dataType: "jsonp",
type: "GET",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", getAuthorizationHeader($("#user").val(), $("#password").val()));
},
success: ajaxSuccessHandler,
error: ajaxErrHandler
});
});
});
</script>
对于迟到的回复感到抱歉......我正在按照建议尝试使用CORS,但由于我的客户端发送的标头不包含Origin,我肯定会遗漏一些明显的东西。这是我所做的,使用http://brockallen.com/2012/06/28/cors-support-in-webapi-mvc-and-iis-with-thinktecture-identitymodel/中的库:
我创建了一个新的MVC4互联网应用程序来测试这个场景,并使用NuGet添加Thinktecture.IdentityModel。
我创建了这个CorsConfig类:
static public class CorsConfig
{
public static void RegisterCorsForWebApi(HttpConfiguration httpConfig)
{
WebApiCorsConfiguration corsConfig = new WebApiCorsConfiguration();
// this adds the CorsMessageHandler to the HttpConfiguration’s
// MessageHandlers collection
corsConfig.RegisterGlobal(httpConfig);
corsConfig
.ForResources("Products")
.ForOrigins("http://hello.net")
.AllowAll();
}
public static void RegisterCorsForMvc(MvcCorsConfiguration corsConfig)
{
corsConfig
.ForResources("Products.GetProducts")
.ForOrigins("http://hello.net")
.AllowAll();
}
}
我调用了这个类的两个方法。
添加:
我在MVC控制器中创建一个简单的动作方法,返回一些JSON。我打算稍后在[授权]进行装饰,一旦在客户端正确调用,我就可以测试身份验证(和授权,添加角色)。
在视图中,我将我的方法称为:
// this adds the CorsMessageHandler to the HttpConfiguration’s
// MessageHandlers collection
corsConfig.RegisterGlobal(httpConfig);
corsConfig
.ForResources("Products")
.ForOrigins("http://hello.net")
.AllowAll();
}
public static void RegisterCorsForMvc(MvcCorsConfiguration corsConfig)
{
corsConfig
.ForResources("Products.GetProducts")
.ForOrigins("http://hello.net")
.AllowAll();
}
然而,检查标题我看不到起源。另外,对于对MVC操作/ WebApi的CORS调用,这是传递凭证(当然在现实世界中这将是HTTPS)的正确方法吗?