AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / server / Perguntas / 1169659
Accepted
suchislife
suchislife
Asked: 2025-01-01 02:12:37 +0800 CST2025-01-01 02:12:37 +0800 CST 2025-01-01 02:12:37 +0800 CST

O módulo Basic Auth do Ubuntu NGINX 1.24.0 não está mais incluso. Como habilitar?

  • 772

Não consigo encontrar essas informações on-line sobre qual versão o nginx aproveitou para incluir o http_auth_basic_modulecomo uma opção de configuração. Além disso, como faço para habilitá-lo? Ou de onde posso baixar módulos?

Configuração do servidor:

nginx -V

nginx version: nginx/1.24.0 (Ubuntu)
built with OpenSSL 3.0.13 30 Jan 2024
TLS SNI support enabled
./configure \
--with-cc-opt='-g -O2 -fno-omit-frame-pointer -mno-omit-leaf-frame-pointer -ffile-prefix-map=/build/nginx-DlMnQR/nginx-1.24.0=. -flto=auto -ffat-lto-objects -fstack-protector-strong -fstack-clash-protection -Wformat -Werror=format-security -fcf-protection -fdebug-prefix-map=/build/nginx-DlMnQR/nginx-1.24.0=/usr/src/nginx-1.24.0-2ubuntu7.1 -fPIC -Wdate-time -D_FORTIFY_SOURCE=3' \
--with-ld-opt='-Wl,-Bsymbolic-functions -flto=auto -ffat-lto-objects -Wl,-z,relro -Wl,-z,now -fPIC' \
--prefix=/usr/share/nginx \
--conf-path=/etc/nginx/nginx.conf \
--http-log-path=/var/log/nginx/access.log \
--error-log-path=stderr \
--lock-path=/var/lock/nginx.lock \
--pid-path=/run/nginx.pid \
--modules-path=/usr/lib/nginx/modules \
--http-client-body-temp-path=/var/lib/nginx/body \
--http-fastcgi-temp-path=/var/lib/nginx/fastcgi \
--http-proxy-temp-path=/var/lib/nginx/proxy \
--http-scgi-temp-path=/var/lib/nginx/scgi \
--http-uwsgi-temp-path=/var/lib/nginx/uwsgi \
--with-compat \
--with-debug \
--with-pcre-jit \
--with-http_ssl_module \
--with-http_stub_status_module \
--with-http_realip_module \
--with-http_auth_request_module \
--with-http_v2_module \
--with-http_dav_module \
--with-http_slice_module \
--with-threads \
--with-http_addition_module \
--with-http_flv_module \
--with-http_gunzip_module \
--with-http_gzip_static_module \
--with-http_mp4_module \
--with-http_random_index_module \
--with-http_secure_link_module \
--with-http_sub_module \
--with-mail_ssl_module \
--with-stream_ssl_module \
--with-stream_ssl_preread_module \
--with-stream_realip_module \
--with-http_geoip_module=dynamic \
--with-http_image_filter_module=dynamic \
--with-http_perl_module=dynamic \
--with-http_xslt_module=dynamic \
--with-mail=dynamic \
--with-stream=dynamic \
--with-stream_geoip_module=dynamic

Usando grep para pesquisar:

nginx -V 2>&1 | grep http_auth_basic_module

Resultado:

Not found

GitHub - /src/http/modules/ngx_http_auth_basic_module.c

Teste de configuração do NGINX

# info.nginx
location = "/info.nginx" {

    auth_basic           "Administrator's Area";
    auth_basic_user_file /etc/nginx/.htpasswd;

    access_log    off;
    default_type  "application/json; charset=UTF-8";
    return        200 '{"nginx_version":"$nginx_version","time":{"time_iso8601":"$time_iso8601","time_local":"$time_local","msec":"$msec"},"remote":{"remote_addr":"$remote_addr","remote_port":"$remote_port"},"host":{"host":"$host","hostname":"$hostname"},"server":{"server_addr":"$server_addr","server_name":"$server_name","server_port":"$server_port","server_protocol":"$server_protocol"},"request":{"request_time":"$request_time","request_method":"$request_method","request_uri":"$request_uri","request_filename":"$request_filename","uri":"$uri","query_string":"$query_string","realpath_root":"$realpath_root"},"document":{"document_root":"$document_root","document_uri":"$document_uri"}}';
}
nginx
  • 2 2 respostas
  • 151 Views

2 respostas

  • Voted
  1. Best Answer
    Ivan Shatsky
    2025-01-03T18:45:43+08:002025-01-03T18:45:43+08:00

    Conforme mencionado anteriormente , de acordo com a descrição das fases de processamento de requisição do guia de desenvolvimento nginx , a returndiretiva é executada durante o NGX_HTTP_REWRITE_PHASE, enquanto as auth_...diretivas entram em vigor durante o posterior NGX_HTTP_ACCESS_PHASE. Como alternativa, você pode usar a try_filesdiretiva para pular para outro local durante o posterior NGX_HTTP_PRECONTENT_PHASE(veja esta resposta para detalhes):

    # info.nginx
    location = /info.nginx {
        auth_basic           "Administrator's Area";
        auth_basic_user_file /etc/nginx/.htpasswd;
        try_files "" @info_nginx;
    }
    location @info_nginx {
        access_log    off;
        default_type  "application/json; charset=UTF-8";
        return        200 '{"nginx_version":"$nginx_version","time":{"time_iso8601":"$time_iso8601","time_local":"$time_local","msec":"$msec"},"remote":{"remote_addr":"$remote_addr","remote_port":"$remote_port"},"host":{"host":"$host","hostname":"$hostname"},"server":{"server_addr":"$server_addr","server_name":"$server_name","server_port":"$server_port","server_protocol":"$server_protocol"},"request":{"request_time":"$request_time","request_method":"$request_method","request_uri":"$request_uri","request_filename":"$request_filename","uri":"$uri","query_string":"$query_string","realpath_root":"$realpath_root"},"document":{"document_root":"$document_root","document_uri":"$document_uri"}}';
    }
    

    Além da resposta, posso dizer que se o nginx fosse realmente compilado sem o módulo de autenticação básico, sua configuração falharia na validação na inicialização e o nginx retornaria um erro comonginx: [emerg] unknown directive "auth_basic" in ...

    • 1
  2. suchislife
    2025-01-01T11:59:57+08:002025-01-01T11:59:57+08:00

    Alternativa - Usando um mapa para validar credenciais de autenticação básicas

    Lógica:

    1. Qualquer cabeçalho HTTP recebido se torna uma variável com: $http_<header_name>.
    2. Portanto, qualquer Authorizationcabeçalho recebido do cliente se torna $http_authorization.
    3. Munidos desse conhecimento, criamos um mapa dentro do http{...}contexto.
    4. Em seguida, mapeamos o Authorizationcabeçalho para uma variável chamada $auth_status.
    5. Se o Authorizationcabeçalho exato não estiver presente, o mapa será avaliado como "unauthorized".
    http {
        map $http_authorization $auth_status {
    
            # Basic base64(admin:secret)
            "Basic YWRtaW46c2VjcmV0" "authorized";
    
            # Basic base64(user1:secret)
            "Basic dXNlcjE6c2VjcmV0" "authorized";
    
            # Basic base64(user2:secret)
            "Basic dXNlcjI6c2VjcmV0" "authorized";
    
            # Basic base64(user3:secret)
            "Basic dXNlcjM6c2VjcmV0" "authorized";
    
            # Default unauthorized
            default "unauthorized";
    
        }
    }
    
    1. Usamos $auth_statuspara proteger um locationbloco dentro do server {...}contexto:
    server {
    
        # info.nginx
        location = "/info.nginx" {
    
            # HTTP 401: Unauthorized
            if ($auth_status = "unauthorized") {
                return 401;
            }
    
            # HTTP 200: OK
            access_log    off;
    
            default_type  "application/json; charset=UTF-8";
            return 200 '{"nginx_version":"$nginx_version","remote_user":"$remote_user", "http_authorization": "$http_authorization","time":{"time_iso8601":"$time_iso8601","time_local":"$time_local","msec":"$msec"},"remote":{"remote_addr":"$remote_addr","remote_port":"$remote_port"},"host":{"host":"$host","hostname":"$hostname"},"server":{"server_addr":"$server_addr","server_name":"$server_name","server_port":"$server_port","server_protocol":"$server_protocol"},"request":{"request_time":"$request_time","request_method":"$request_method","request_uri":"$request_uri","request_filename":"$request_filename","uri":"$uri","query_string":"$query_string","realpath_root":"$realpath_root"},"document":{"document_root":"$document_root","document_uri":"$document_uri"}}';
    
        }
    }
    
    1. Por fim, criamos um HTTP 401 personalizado error_pagedentro do server {...}contexto e adicionamos o WWW-Authenticatecabeçalho para acionar o prompt de login de autenticação básica do navegador.
    error_page 401 /401-nginx.html;
    
    location = "/401-nginx.html" {
        root var/www/internal;
        internal;
        add_header WWW-Authenticate 'Basic realm="Restricted Area"' always;
    }
    
    • 0

relate perguntas

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Você pode passar usuário/passar para autenticação básica HTTP em parâmetros de URL?

    • 5 respostas
  • Marko Smith

    Ping uma porta específica

    • 18 respostas
  • Marko Smith

    Verifique se a porta está aberta ou fechada em um servidor Linux?

    • 7 respostas
  • Marko Smith

    Como automatizar o login SSH com senha?

    • 10 respostas
  • Marko Smith

    Como posso dizer ao Git para Windows onde encontrar minha chave RSA privada?

    • 30 respostas
  • Marko Smith

    Qual é o nome de usuário/senha de superusuário padrão para postgres após uma nova instalação?

    • 5 respostas
  • Marko Smith

    Qual porta o SFTP usa?

    • 6 respostas
  • Marko Smith

    Linha de comando para listar usuários em um grupo do Windows Active Directory?

    • 9 respostas
  • Marko Smith

    O que é um arquivo Pem e como ele difere de outros formatos de arquivo de chave gerada pelo OpenSSL?

    • 3 respostas
  • Marko Smith

    Como determinar se uma variável bash está vazia?

    • 15 respostas
  • Martin Hope
    Davie Ping uma porta específica 2009-10-09 01:57:50 +0800 CST
  • Martin Hope
    kernel O scp pode copiar diretórios recursivamente? 2011-04-29 20:24:45 +0800 CST
  • Martin Hope
    Robert ssh retorna "Proprietário incorreto ou permissões em ~/.ssh/config" 2011-03-30 10:15:48 +0800 CST
  • Martin Hope
    Eonil Como automatizar o login SSH com senha? 2011-03-02 03:07:12 +0800 CST
  • Martin Hope
    gunwin Como lidar com um servidor comprometido? 2011-01-03 13:31:27 +0800 CST
  • Martin Hope
    Tom Feiner Como posso classificar a saída du -h por tamanho 2009-02-26 05:42:42 +0800 CST
  • Martin Hope
    Noah Goodrich O que é um arquivo Pem e como ele difere de outros formatos de arquivo de chave gerada pelo OpenSSL? 2009-05-19 18:24:42 +0800 CST
  • Martin Hope
    Brent Como determinar se uma variável bash está vazia? 2009-05-13 09:54:48 +0800 CST

Hot tag

linux nginx windows networking ubuntu domain-name-system amazon-web-services active-directory apache-2.4 ssh

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve