我的 Django 应用程序模板中有一个典型的登录表单(它直接使用Bootstrap,而不是通过某些插件):
<form class="form-signin" method="post" action="/site_manager/login/" id="form-signin"> {% csrf_token %}
<h2 class="form-signin-heading">Please sign in</h2>
<div class="control-group">
<label class="control-label" for="login">Login:</label>
<div class="controls">
<input size="50" name="username" id="username" required="true" type="text" class="form-control" placeholder="Login" intermediateChanges=false>
</div>
</div>
<div class="control-group">
<label class="control-label" for="password">Password:</label>
<div class="controls">
<input size="50" name="password" id="password" required="true" type="password" class="form-control" placeholder="Password" intermediateChanges=false>
</div>
</div>
<button name="submit" id="submit" value="Log in" type="submit" class="btn btn-primary pull-right">Sign in</button>
</form>
这是通过请求模块执行远程身份验证的相应视图:
def login_view(request):
if request.POST:
username = request.POST.get('username')
password = request.POST.get('password')
headers = {'content-type': 'application/json', 'username':username, 'password':password}
r = requests.get(remote_server_url, auth=(username, password), headers=headers)
if r.status_code == 200:
user = authenticate(username=username, password=password)
if user == None:
user = User.objects.create_user(username.encode('ascii', 'ignore'), "", password)
user = authenticate(username=username, password=password)
login(request, user)
request.session.set_expiry(0)
return HttpResponseRedirect('<index_page>')
else:
# redirects back to login page with some error message
登录成功后,我可以使用 Javascript 查询 CSRF 令牌,如此处所述,我的计划是出于其他目的(例如,RESTful 查询)对远程服务器(通过 SSL)进行 Ajax 调用。正如上面的代码所示,该服务器使用基本身份验证。所以我想在每次Ajax调用的header中设置CSRF token,但这不遵循同源原则:
var csrftoken = $.cookie('csrftoken'); // using the jQuery Cookie plugin
$.ajaxSetup({
headers: {
'Authorization': "Basic XXXXX"
}
beforeSend: function(xhr, settings) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
});
$.ajax({
type: "GET",
dataType: "jsonp",
url: remote_server_url+'/api/v1/someRESTfulResource/',
contentType: 'application/json',
success: function(data){
// some operations with data
}
});
在remote_server_url
Ajax 调用中使用的和身份验证是一样的,它与 Django 应用程序不共享同一个域。据我所知,这是一个安全风险。出于同样的原因,我也不想在 Javascript 代码中提供纯文本密码。如何使用用户凭据安全地对远程服务器进行 Ajax 调用?