从中间件中触发基本的HTTP身份验证 [英] Trigger basic HTTP auth from within middleware

查看:93
本文介绍了从中间件中触发基本的HTTP身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为rails创建了一个自定义中间件,该中间件将拦截所有请求并确保其来自授权IP,否则它将提示您输入基本的http auth用户/名称密码.

I have created a custom middleware for rails which will intercept all requests and make sure it's coming from an authorized IP, otherwise it should prompt for a basic http auth user/name password.

这是当前的样子:

require 'net/http'

class AuthorizeEnvironment
  def initialize(app)
    @app = app
  end

  def call(env)
    if AppConstants.approved_doximity_ips.include?(env["REMOTE_ADDR"])
      @app.call(env)
    elsif authorized?(env)
      @app.call(env)
    else
      [403, {"Content-Type" => "text/html"}, ["Not Authorized on this environment."]]
    end
  end

  def authorized?(env)
    @auth ||= Rack::Auth::Basic::Request.new(env)
    @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == ['username', 'password']
  end
end

此代码的问题是,我似乎找不到在浏览器上触发http身份验证窗口的方法.我查看了,但没有看到任何明显的迹象表明如何做到这一点.

The issue with this code is that I can't seem to find a way to trigger the http auth window on the browser. I reviewed this and didn't see any obvious indication of how this is done.

能给我指出正确的方向吗?

Could you please point me in the right direction?

推荐答案

我尚未测试您的代码,但看起来您的回复是403,表示禁止".也就是说,当前登录的用户没有访问此资源的权限.

I haven't tested your code, but it looks like your replying with a 403 which means "forbidden". I.e., the currently logged in user does not have permissions to access this resource.

从RFC( http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html )

服务器理解了该请求,但拒绝执行该请求.授权将无济于事,并且不应重复该请求.如果请求方法不是HEAD,并且服务器希望公开为什么未满足请求,则应在实体中描述拒绝原因.如果服务器不希望将此信息提供给客户端,则可以使用状态代码404(未找到)代替.

The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.

相反,您需要使用401,并且仅当当前登录的用户无法访问资源时才用403答复.

Instead, you need to use a 401, and only reply with a 403 ONLY if the currently logged in user cannot access the resource.

这篇关于从中间件中触发基本的HTTP身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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