1//
2// HTTPBasicCredentials.cpp
3//
4// Library: Net
5// Package: HTTP
6// Module: HTTPBasicCredentials
7//
8// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
9// and Contributors.
10//
11// SPDX-License-Identifier: BSL-1.0
12//
13
14
15#include "Poco/Net/HTTPBasicCredentials.h"
16#include "Poco/Net/HTTPRequest.h"
17#include "Poco/Net/NetException.h"
18#include "Poco/Base64Encoder.h"
19#include "Poco/Base64Decoder.h"
20#include "Poco/String.h"
21#include <sstream>
22
23
24using Poco::Base64Decoder;
25using Poco::Base64Encoder;
26using Poco::icompare;
27
28
29namespace Poco {
30namespace Net {
31
32
33const std::string HTTPBasicCredentials::SCHEME = "Basic";
34
35
36HTTPBasicCredentials::HTTPBasicCredentials()
37{
38}
39
40
41HTTPBasicCredentials::HTTPBasicCredentials(const std::string& username, const std::string& password):
42 _username(username),
43 _password(password)
44{
45}
46
47
48HTTPBasicCredentials::HTTPBasicCredentials(const HTTPRequest& request)
49{
50 std::string scheme;
51 std::string authInfo;
52 request.getCredentials(scheme, authInfo);
53 if (icompare(scheme, SCHEME) == 0)
54 {
55 parseAuthInfo(authInfo);
56 }
57 else throw NotAuthenticatedException("Basic authentication expected");
58}
59
60
61HTTPBasicCredentials::HTTPBasicCredentials(const std::string& authInfo)
62{
63 parseAuthInfo(authInfo);
64}
65
66
67HTTPBasicCredentials::~HTTPBasicCredentials()
68{
69}
70
71
72void HTTPBasicCredentials::setUsername(const std::string& username)
73{
74 _username = username;
75}
76
77
78void HTTPBasicCredentials::setPassword(const std::string& password)
79{
80 _password = password;
81}
82
83
84void HTTPBasicCredentials::authenticate(HTTPRequest& request) const
85{
86 std::ostringstream ostr;
87 Base64Encoder encoder(ostr);
88 encoder.rdbuf()->setLineLength(0);
89 encoder << _username << ":" << _password;
90 encoder.close();
91 request.setCredentials(SCHEME, ostr.str());
92}
93
94
95void HTTPBasicCredentials::proxyAuthenticate(HTTPRequest& request) const
96{
97 std::ostringstream ostr;
98 Base64Encoder encoder(ostr);
99 encoder.rdbuf()->setLineLength(0);
100 encoder << _username << ":" << _password;
101 encoder.close();
102 request.setProxyCredentials(SCHEME, ostr.str());
103}
104
105
106void HTTPBasicCredentials::parseAuthInfo(const std::string& authInfo)
107{
108 static const int eof = std::char_traits<char>::eof();
109
110 std::istringstream istr(authInfo);
111 Base64Decoder decoder(istr);
112 int ch = decoder.get();
113 while (ch != eof && ch != ':')
114 {
115 _username += (char) ch;
116 ch = decoder.get();
117 }
118 if (ch == ':') ch = decoder.get();
119 while (ch != eof)
120 {
121 _password += (char) ch;
122 ch = decoder.get();
123 }
124}
125
126
127} } // namespace Poco::Net
128