Skip to content

Commit

Permalink
Authentication with apitoken (#139)
Browse files Browse the repository at this point in the history
* Changed authentication from cookie based to auth header based. Removed no more necessary tests.

* Renamed password to apiToken everywhere

* Added JiraApiRequester test for Authenticated Requests (both valid and wrong credentials)

* Restored failing test accidentally removed (nothing to do with authentication)

* Fix JiraClient.Authenticate return. Restored JiraClient.Authenticate tests. Reset JiraTimeHelpers.Configuration to null in JiraTimeHelpersTest to avoid misformatting errors.
  • Loading branch information
bellamatte authored and carstengehling committed May 4, 2019
1 parent 24e7486 commit 6ca0ba6
Show file tree
Hide file tree
Showing 16 changed files with 151 additions and 282 deletions.
2 changes: 1 addition & 1 deletion source/StopWatch/App.config
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ limitations under the License.
<setting name="Username" serializeAs="String">
<value />
</setting>
<setting name="Password" serializeAs="String">
<setting name="ApiToken" serializeAs="String">
<value />
</setting>
<setting name="JiraBaseUrl" serializeAs="String">
Expand Down
2 changes: 0 additions & 2 deletions source/StopWatch/Jira/IJiraApiRequestFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,6 @@ internal interface IJiraApiRequestFactory
IRestRequest CreateGetIssueTimetrackingRequest(string key);
IRestRequest CreatePostWorklogRequest(string key, DateTimeOffset started, TimeSpan time, string comment, EstimateUpdateMethods adjustmentMethod, string adjustmentValue);
IRestRequest CreatePostCommentRequest(string key, string comment);
IRestRequest CreateAuthenticateRequest(string username, string password);
IRestRequest CreateReAuthenticateRequest();
IRestRequest CreateGetAvailableTransitions(string key);
IRestRequest CreateDoTransition(string key, int transitionId);
IRestRequest CreateGetConfigurationRequest();
Expand Down
2 changes: 2 additions & 0 deletions source/StopWatch/Jira/IJiraApiRequester.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,7 @@ interface IJiraApiRequester

T DoAuthenticatedRequest<T>(IRestRequest request)
where T : new();

void SetAuthentication(string username, string apiToken);
}
}
31 changes: 0 additions & 31 deletions source/StopWatch/Jira/JiraApiRequestFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,12 @@ limitations under the License.

namespace StopWatch
{
internal class AuthenticateNotYetCalledException : Exception
{
}

internal class JiraApiRequestFactory : IJiraApiRequestFactory
{
#region public methods
public JiraApiRequestFactory(IRestRequestFactory restRequestFactory)
{
this.restRequestFactory = restRequestFactory;
this.username = "";
this.password = "";
}


Expand Down Expand Up @@ -135,36 +129,11 @@ public IRestRequest CreateDoTransition(string key, int transitionId)
);
return request;
}

public IRestRequest CreateAuthenticateRequest(string username, string password)
{
this.username = username;
this.password = password;

var request = restRequestFactory.Create("/rest/auth/1/session", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody(new {
username = this.username,
password = this.password
});
return request;
}

public IRestRequest CreateReAuthenticateRequest()
{
if (string.IsNullOrEmpty(this.username))
throw new AuthenticateNotYetCalledException();

return CreateAuthenticateRequest(this.username, this.password);
}
#endregion


#region private members
private IRestRequestFactory restRequestFactory;

private string username;
private string password;
#endregion
}
}
65 changes: 22 additions & 43 deletions source/StopWatch/Jira/JiraApiRequester.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,6 @@ limitations under the License.

namespace StopWatch
{
internal class RequestDeniedException : Exception
{
}


internal class JiraApiRequester : IJiraApiRequester
{
public string ErrorMessage { get; private set; }
Expand All @@ -36,10 +31,11 @@ public JiraApiRequester(IRestClientFactory restClientFactory, IJiraApiRequestFac
ErrorMessage = "";
}


public T DoAuthenticatedRequest<T>(IRestRequest request)
where T : new()
{
AddAuthHeader(request);

IRestClient client = restClientFactory.Create();

_logger.Log(string.Format("Request: {0}", client.BuildUri(request)));
Expand All @@ -49,13 +45,7 @@ public T DoAuthenticatedRequest<T>(IRestRequest request)
// If login session has expired, try to login, and then re-execute the original request
if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.BadRequest)
{
_logger.Log("Try to re-authenticate");
if (!ReAuthenticate())
throw new RequestDeniedException();

_logger.Log(string.Format("Authenticated. Resend request: {0}", client.BuildUri(request)));
response = client.Execute<T>(request);
_logger.Log(string.Format("Response: {0} - {1}", response.StatusCode, StringHelpers.Truncate(response.Content, 100)));
throw new RequestDeniedException();
}

if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Created)
Expand All @@ -68,45 +58,34 @@ public T DoAuthenticatedRequest<T>(IRestRequest request)
return response.Data;
}


protected bool ReAuthenticate()
public void SetAuthentication(string username, string apiToken)
{
IRestRequest request;

try
{
request = jiraApiRequestFactory.CreateReAuthenticateRequest();
}
catch (AuthenticateNotYetCalledException)
{
return false;
}

var client = restClientFactory.Create(true);
_logger.Log(string.Format("Request: {0}", client.BuildUri(request)));
IRestResponse response = client.Execute(request);
_logger.Log(string.Format("Response: {0} - {1}", response.StatusCode, StringHelpers.Truncate(response.Content, 100)));

if (response.StatusCode == HttpStatusCode.Unauthorized)
{
ErrorMessage = "Invalid username or password";
return false;
}
_username = username;
_apiToken = apiToken;
}

if (response.StatusCode != HttpStatusCode.OK)
private void AddAuthHeader(IRestRequest request)
{
if (string.IsNullOrEmpty(_username) || string.IsNullOrEmpty(_apiToken))
{
ErrorMessage = response.ErrorMessage;
return false;
throw new UsernameAndApiTokenNotSetException();
}

ErrorMessage = "";
return true;
request.AddHeader("Authorization", "Basic " + System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{_username}:{_apiToken}")));
}


private Logger _logger = Logger.Instance;

private IRestClientFactory restClientFactory;
private IJiraApiRequestFactory jiraApiRequestFactory;
private string _username;
private string _apiToken;
}

internal class RequestDeniedException : Exception
{
}

internal class UsernameAndApiTokenNotSetException : Exception
{
}
}
20 changes: 5 additions & 15 deletions source/StopWatch/Jira/JiraClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,22 +35,12 @@ public JiraClient(IJiraApiRequestFactory jiraApiRequestFactory, IJiraApiRequeste
}


public bool Authenticate(string username, string password)
public bool Authenticate(string username, string apiToken)
{
SessionValid = false;

var request = jiraApiRequestFactory.CreateAuthenticateRequest(username, password);
try
{
jiraApiRequester.DoAuthenticatedRequest<object>(request);
JiraTimeHelpers.Configuration = GetTimeTrackingConfiguration();
return true;
}
catch (RequestDeniedException)
{
ErrorMessage = jiraApiRequester.ErrorMessage;
return false;
}
jiraApiRequester.SetAuthentication(username, apiToken);
JiraTimeHelpers.Configuration = GetTimeTrackingConfiguration();
return JiraTimeHelpers.Configuration != null;
}


Expand Down Expand Up @@ -85,7 +75,7 @@ public List<Filter> GetFavoriteFilters()
return null;
}
}


public SearchResult GetIssuesByJQL(string jql)
{
Expand Down
6 changes: 3 additions & 3 deletions source/StopWatch/Properties/Settings.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion source/StopWatch/Properties/Settings.settings
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
<Setting Name="Username" Type="System.String" Scope="User">
<Value Profile="(Default)" />
</Setting>
<Setting Name="Password" Type="System.String" Scope="User">
<Setting Name="ApiToken" Type="System.String" Scope="User">
<Value Profile="(Default)" />
</Setting>
<Setting Name="JiraBaseUrl" Type="System.String" Scope="User">
Expand Down
14 changes: 7 additions & 7 deletions source/StopWatch/Settings/Settings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ internal sealed class Settings
public WorklogCommentSetting PostWorklogComment { get; set; }

public string Username { get; set; }
public string Password { get; set; }
public string ApiToken { get; set; }
public bool FirstRun { get; set; }

public int CurrentFilter { get; set; }
Expand Down Expand Up @@ -119,10 +119,10 @@ private void ReadSettings()
this.MinimizeToTray = Properties.Settings.Default.MinimizeToTray;
this.IssueCount = Properties.Settings.Default.IssueCount;
this.Username = Properties.Settings.Default.Username;
if (Properties.Settings.Default.Password != "")
this.Password = DPAPI.Decrypt(Properties.Settings.Default.Password);
if (Properties.Settings.Default.ApiToken != "")
this.ApiToken = DPAPI.Decrypt(Properties.Settings.Default.ApiToken);
else
this.Password = "";
this.ApiToken = "";
this.FirstRun = Properties.Settings.Default.FirstRun;
this.SaveTimerState = (SaveTimerSetting)Properties.Settings.Default.SaveTimerState;
this.PauseOnSessionLock = (PauseAndResumeSetting)Properties.Settings.Default.PauseOnSessionLock;
Expand Down Expand Up @@ -154,10 +154,10 @@ public void Save()
Properties.Settings.Default.IncludeProjectName = this.IncludeProjectName;

Properties.Settings.Default.Username = this.Username;
if (this.Password != "")
Properties.Settings.Default.Password = DPAPI.Encrypt(this.Password);
if (this.ApiToken != "")
Properties.Settings.Default.ApiToken = DPAPI.Encrypt(this.ApiToken);
else
Properties.Settings.Default.Password = "";
Properties.Settings.Default.ApiToken = "";

Properties.Settings.Default.FirstRun = this.FirstRun;
Properties.Settings.Default.SaveTimerState = (int)this.SaveTimerState;
Expand Down
10 changes: 5 additions & 5 deletions source/StopWatch/UI/MainForm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ private void MainForm_Shown(object sender, EventArgs e)
else
{
if (IsJiraEnabled)
AuthenticateJira(this.settings.Username, this.settings.Password);
AuthenticateJira(this.settings.Username, this.settings.ApiToken);
}

InitializeIssueControls();
Expand Down Expand Up @@ -254,7 +254,7 @@ private void lblConnectionStatus_Click(object sender, EventArgs e)


#region private methods
private void AuthenticateJira(string username, string password)
private void AuthenticateJira(string username, string apiToken)
{
Task.Factory.StartNew(
() =>
Expand All @@ -267,7 +267,7 @@ private void AuthenticateJira(string username, string password)
}
);
if (jiraClient.Authenticate(username, password))
if (jiraClient.Authenticate(username, apiToken))
this.InvokeIfRequired(
() => UpdateIssuesOutput(true)
);
Expand Down Expand Up @@ -536,7 +536,7 @@ private void EditSettings()
restClientFactory.BaseUrl = this.settings.JiraBaseUrl;
Logging.Logger.Instance.Enabled = settings.LoggingEnabled;
if (IsJiraEnabled)
AuthenticateJira(this.settings.Username, this.settings.Password);
AuthenticateJira(this.settings.Username, this.settings.ApiToken);
InitializeIssueControls();
}
}
Expand Down Expand Up @@ -691,7 +691,7 @@ private bool IsJiraEnabled
return !(
string.IsNullOrWhiteSpace(settings.JiraBaseUrl) ||
string.IsNullOrWhiteSpace(settings.Username) ||
string.IsNullOrWhiteSpace(settings.Password)
string.IsNullOrWhiteSpace(settings.ApiToken)
);
}
}
Expand Down
Loading

0 comments on commit 6ca0ba6

Please sign in to comment.