1 // SPDX-License-Identifier: Apache-2.0 2 // SPDX-FileCopyrightText: Copyright OpenBMC Authors 3 #pragma once 4 #include "http_response.hpp" 5 #include "http_utility.hpp" 6 #include "sessions.hpp" 7 8 #include <boost/beast/http/field.hpp> 9 #include <boost/beast/http/status.hpp> 10 #include <boost/url/format.hpp> 11 #include <boost/url/url.hpp> 12 13 #include <string_view> 14 15 namespace forward_unauthorized 16 { 17 18 inline bool& hasWebuiRoute() 19 { 20 static bool webuiRoute = false; 21 return webuiRoute; 22 } 23 24 inline void sendUnauthorized(std::string_view url, 25 std::string_view xRequestedWith, 26 std::string_view accept, crow::Response& res) 27 { 28 // If it's a browser connecting, don't send the HTTP authenticate 29 // header, to avoid possible CSRF attacks with basic auth 30 if (http_helpers::isContentTypeAllowed( 31 accept, http_helpers::ContentType::HTML, false /*allowWildcard*/)) 32 { 33 // If we have a webui installed, redirect to that login page 34 if (hasWebuiRoute()) 35 { 36 boost::urls::url forward = 37 boost::urls::format("/?next={}#/login", url); 38 res.result(boost::beast::http::status::temporary_redirect); 39 res.addHeader(boost::beast::http::field::location, 40 forward.buffer()); 41 return; 42 } 43 // If we don't have a webui installed, just return an unauthorized 44 // body 45 res.result(boost::beast::http::status::unauthorized); 46 res.write( 47 "No authentication provided, and no login UI present to forward to."); 48 return; 49 } 50 51 res.result(boost::beast::http::status::unauthorized); 52 53 // XHR requests from a browser will set the X-Requested-With header when 54 // doing their requests, even though they might not be requesting html. 55 if (!xRequestedWith.empty()) 56 { 57 return; 58 } 59 // if basic auth is disabled, don't propose it. 60 if (!persistent_data::SessionStore::getInstance() 61 .getAuthMethodsConfig() 62 .basic) 63 { 64 return; 65 } 66 res.addHeader(boost::beast::http::field::www_authenticate, "Basic"); 67 } 68 } // namespace forward_unauthorized 69