Skip to content
This repository has been archived by the owner on Mar 11, 2020. It is now read-only.

Commit

Permalink
codacy fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
henalbrod committed Oct 22, 2019
1 parent 9ec851b commit efc0e6a
Show file tree
Hide file tree
Showing 22 changed files with 162 additions and 133 deletions.
2 changes: 1 addition & 1 deletion examples/Examples.AspNetCoreHosted/Client/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace Examples.AspNetCoreHosted.Client
{
public class Program
public static class Program
{
public static void Main(string[] args)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,6 @@ public class WeatherForecastController : ControllerBase
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

private readonly ILogger<WeatherForecastController> logger;

public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
this.logger = logger;
}

[HttpGet]
[Authorize("read:weather_forecast")]
public IEnumerable<WeatherForecast> Get()
Expand Down
2 changes: 1 addition & 1 deletion examples/Examples.AspNetCoreHosted/Server/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

namespace Examples.AspNetCoreHosted.Server
{
public class Program
public static class Program
{
public static void Main(string[] args)
{
Expand Down
2 changes: 1 addition & 1 deletion examples/Examples.ClientSide/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace Examples.ClientSide
{
public class Program
public static class Program
{
public static void Main(string[] args)
{
Expand Down
2 changes: 1 addition & 1 deletion examples/Examples.ServerSide/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

namespace Examples.ServerSide
{
public class Program
public static class Program
{
public static void Main(string[] args)
{
Expand Down
5 changes: 1 addition & 4 deletions examples/Examples.ServerSide/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,13 @@
"Domain": "[Auth0_Audience]",
"ClientId": "[Auth0_Client_Id]",
"Audience": "[Auth0_Audience]",
"ClientSecret": "[Auth0_Client_Secret]",

"ClientSecret": "[Auth0_Client_Secret]"
//// Uncomment the following line if you don't want your unauthenticated users to be automatically redirected to Auth0's Universal Login page
// "RequireAuthenticatedUser": false

/// Uncomment the following line if you don't want your users to be automatically logged-off on token expiration
// "SlidingExpiration": true
},


"Logging": {
"LogLevel": {
"Default": "Information",
Expand Down
40 changes: 19 additions & 21 deletions src/Blazor.Auth0.ClientSide/Authentication.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ namespace Blazor.Auth0
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
Expand Down Expand Up @@ -49,7 +50,7 @@ public static string BuildAuthorizeUrl(AuthorizeOptions buildAuthorizedUrlOption
query = query.Add("state", buildAuthorizedUrlOptions.State);
query = query.Add("nonce", buildAuthorizedUrlOptions.Nonce);
query = query.Add("client_id", buildAuthorizedUrlOptions.ClientID);
query = query.Add("scope", buildAuthorizedUrlOptions.Scope);
query = query.Add("scope", buildAuthorizedUrlOptions.Scope);

if (buildAuthorizedUrlOptions.CodeChallengeMethod != CodeChallengeMethods.None)
{
Expand All @@ -76,7 +77,7 @@ public static string BuildAuthorizeUrl(AuthorizeOptions buildAuthorizedUrlOption

query = query.Add("redirect_uri", buildAuthorizedUrlOptions.RedirectUri);

UriBuilder uriBuilder = new UriBuilder()
UriBuilder uriBuilder = new UriBuilder
{
Scheme = "https",
Host = buildAuthorizedUrlOptions.Domain,
Expand Down Expand Up @@ -218,23 +219,20 @@ public static ParsedHash ParseHash(ParseHashOptions parseHashOptions)

Uri absoluteUri = parseHashOptions.AbsoluteUri;
string hash;
switch (parseHashOptions.ResponseType)
if (parseHashOptions.ResponseType == ResponseTypes.Code)
{
case ResponseTypes.Code:
hash = !string.IsNullOrEmpty(absoluteUri.Query) ? absoluteUri.Query.Remove(0, 1) : null;
break;
default:
{
string[] fragments = absoluteUri.AbsoluteUri.Split('#');

if (fragments.Length < 2)
{
return null;
}
}
else
{
string[] fragments = absoluteUri.AbsoluteUri.Split('#');

hash = fragments[1];
break;
if (fragments.Length < 2)
{
return null;
}

hash = fragments[1];
}

if (string.IsNullOrEmpty(hash))
Expand All @@ -252,7 +250,7 @@ public static ParsedHash ParseHash(ParseHashOptions parseHashOptions)

error += !string.IsNullOrEmpty(result.State) ? $"; state: {result.State}" : string.Empty;

throw new Exception(error);
throw new AuthenticationException(error);
}

if (
Expand All @@ -266,12 +264,12 @@ public static ParsedHash ParseHash(ParseHashOptions parseHashOptions)

if ((parseHashOptions.ResponseType == ResponseTypes.Token || parseHashOptions.ResponseType == ResponseTypes.TokenAndIdToken) && string.IsNullOrEmpty(result.AccessToken))
{
throw new Exception(Resources.InvalidHashMissingAccessTokenError);
throw new AuthenticationException(Resources.InvalidHashMissingAccessTokenError);
}

if ((parseHashOptions.ResponseType == ResponseTypes.Token || parseHashOptions.ResponseType == ResponseTypes.TokenAndIdToken) && string.IsNullOrEmpty(result.IdToken))
{
throw new Exception(Resources.InvalidHashMissingIdTokenError);
throw new AuthenticationException(Resources.InvalidHashMissingIdTokenError);
}

return result;
Expand Down Expand Up @@ -307,7 +305,7 @@ public static void ValidateAuthorizationResponse(AuthorizationResponse authoriza
// Validate Error
if (errorDescription == null && !string.IsNullOrEmpty(authorizationResponse.Error))
{
switch (authorizationResponse.Error.ToLower())
switch (authorizationResponse.Error.ToLowerInvariant())
{
case "login_required":

Expand All @@ -333,7 +331,7 @@ public static void ValidateAuthorizationResponse(AuthorizationResponse authoriza

if (!string.IsNullOrEmpty(errorDescription))
{
throw new ApplicationException(errorDescription);
throw new AuthenticationException(errorDescription);
}
}

Expand All @@ -353,7 +351,7 @@ public static bool ValidateAccessTokenHash(string atHash, string accessToken)
{
byte[] hashValue = mySHA256.ComputeHash(Encoding.ASCII.GetBytes(accessToken));
string base64Encoded = Convert.ToBase64String(hashValue.Take(16).ToArray());
accessTokenHash = Convert.ToBase64String(hashValue.Take(16).ToArray()).TrimEnd('=').Replace('+', '-').Replace('/', '_');
accessTokenHash = base64Encoded.TrimEnd('=').Replace('+', '-').Replace('/', '_');
}

return accessTokenHash.Equals(atHash);
Expand Down
62 changes: 28 additions & 34 deletions src/Blazor.Auth0.ClientSide/AuthenticationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ namespace Blazor.Auth0
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Authentication;
using System.Security.Claims;
using System.Security.Principal;
using System.Text.Json;
Expand Down Expand Up @@ -77,7 +78,7 @@ private set
/// <param name="navigationManager">A <see cref="NavigationManager"/> param.</param>
/// <param name="options">A <see cref="ClientOptions"/> param.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.OrderingRules", "SA1201:Elements should appear in the correct order", Justification = "I like this best ;)")]
public AuthenticationService(ILogger<AuthenticationService> logger, HttpClient httpClient, IJSRuntime jsRuntime, NavigationManager navigationManager, ClientOptions options)
public AuthenticationService(ILogger<AuthenticationService> logger, HttpClient httpClient, IJSRuntime jsRuntime, NavigationManager navigationManager, ClientOptions options)
{
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
this.httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
Expand Down Expand Up @@ -107,7 +108,13 @@ public async Task Authorize()
}

/// <inheritdoc/>
public async Task LogOut(string redirectUri = null)
public async Task LogOut()
{
await this.LogOut(null).ConfigureAwait(false);
}

/// <inheritdoc/>
public async Task LogOut(string redirectUri)
{
string logoutUrl = CommonAuthentication.BuildLogoutUrl(this.clientOptions.Domain, this.clientOptions.ClientId, redirectUri);

Expand All @@ -121,6 +128,10 @@ public async Task LogOut(string redirectUri = null)
{
await this.Authorize().ConfigureAwait(false);
}
else
{
// There's no redirectUri and an authenticated user is not required
}

if (this.clientOptions.RequireAuthenticatedUser)
{
Expand All @@ -135,10 +146,8 @@ public Task<AuthenticationState> GetAuthenticationStateAsync()
{
GenericIdentity identity = null;

switch (this.SessionState)
if (this.SessionState == SessionStates.Active)
{
case SessionStates.Active:

identity = new GenericIdentity(this.User?.Name ?? string.Empty, "JWT");

if (!string.IsNullOrEmpty(this.User.Sub?.Trim()))
Expand Down Expand Up @@ -235,14 +244,10 @@ public Task<AuthenticationState> GetAuthenticationStateAsync()
identity.AddClaims(this.User.CustomClaims.Select(customClaim => new Claim(customClaim.Key, customClaim.Value.GetRawText(), customClaim.Value.ValueKind.ToString())));

identity.AddClaims(this.User.Permissions.Select(permission => new Claim($"{permission}", "true", "permissions")));

break;
case SessionStates.Undefined:
case SessionStates.Inactive:

}
else
{
identity = new GenericIdentity(string.Empty, "JWT");

break;
}

return Task.FromResult(new AuthenticationState(new ClaimsPrincipal(identity)));
Expand Down Expand Up @@ -319,7 +324,7 @@ public async Task HandleAuthorizationResponseAsync(AuthorizationResponse authori

this.ScheduleLogOut();
}
catch (ApplicationException ex)
catch (AuthenticationException ex)
{
await this.OnLoginRequestValidationError(authorizationResponse.Error, ex.Message).ConfigureAwait(false);
}
Expand Down Expand Up @@ -351,7 +356,7 @@ private async Task<SessionInfo> GetSessionInfoAsync(AuthorizationResponse author
return await this.GetSessionInfoAsync(authorizationResponse.Code).ConfigureAwait(false);
}

return new SessionInfo()
return new SessionInfo
{
AccessToken = authorizationResponse.AccessToken,
ExpiresIn = authorizationResponse.ExpiresIn,
Expand Down Expand Up @@ -401,20 +406,20 @@ private void ValidateIdToken(UserInfo idTokenInfo, string accessToken)

if (nonceIsValid.HasValue && !nonceIsValid.Value)
{
throw new ApplicationException(Resources.InvalidNonceError);
throw new AuthenticationException(Resources.InvalidNonceError);
}

if (string.IsNullOrEmpty(idTokenInfo.AtHash))
if (string.IsNullOrEmpty(idTokenInfo?.AtHash))
{
Console.WriteLine(Resources.NotAltChashWarning);
this.logger.LogWarning(Resources.NotAltChashWarning);
}
else
{
bool atHashIsValid = Authentication.ValidateAccessTokenHash(idTokenInfo.AtHash, accessToken);
bool atHashIsValid = Authentication.ValidateAccessTokenHash(idTokenInfo?.AtHash, accessToken);

if (!atHashIsValid)
{
throw new ApplicationException(Resources.InvalidAccessTokenHashError);
throw new AuthenticationException(Resources.InvalidAccessTokenHashError);
}
}
}
Expand Down Expand Up @@ -442,9 +447,9 @@ private async Task OnLoginRequestValidationError(string error, string validation
{
this.ClearSession();

Console.WriteLine("Login Error: " + validationMessage);
this.logger.LogError("Login Error: " + validationMessage);

if (error.ToLower() == "login_required" && this.clientOptions.RequireAuthenticatedUser)
if (error.ToLowerInvariant() == "login_required" && this.clientOptions.RequireAuthenticatedUser)
{
await this.Authorize().ConfigureAwait(false);
System.Threading.Thread.Sleep(30000);
Expand Down Expand Up @@ -546,7 +551,7 @@ private string BuildRedirectUrl()
}

#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
private bool disposedValue; // To detect redundant calls

protected virtual void Dispose(bool disposing)
{
Expand All @@ -555,28 +560,17 @@ protected virtual void Dispose(bool disposing)
if (disposing)
{
// TODO: dispose managed state (managed objects).

this.dotnetObjectRef.Dispose();
this.httpClient.Dispose();
((IDisposable)this.logOutTimer).Dispose();
this.logOutTimer?.Dispose();
}

// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
// TODO: set large fields to null.

this.disposedValue = true;
}
}

// TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
// ~AuthenticationService()
// {
// // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }

// This code added to correctly implement the disposable pattern.

/// <inheritdoc/>
public void Dispose()
{
Expand Down
5 changes: 4 additions & 1 deletion src/Blazor.Auth0.ClientSide/Blazor.Auth0.ClientSide.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@


<ItemGroup>
<PackageReference Include="Blazor-Auth0-Shared" Version="1.0.0-Preview3" />
<PackageReference Include="Microsoft.AspNetCore.Components" Version="3.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Components.Web" Version="3.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Components.Authorization" Version="3.0.0" />
Expand Down Expand Up @@ -52,6 +51,10 @@
<AdditionalFiles Include="stylecop.json" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Blazor.Auth0.Shared\Blazor.Auth0.Shared.csproj" />
</ItemGroup>

<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
Expand Down
3 changes: 1 addition & 2 deletions src/Blazor.Auth0.ClientSide/BlazorAuth0BuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public static class BlazorAuth0BuilderExtensions
/// <param name="services">The <see cref="IServiceCollection"/> instance.</param>
/// <param name="options">The <see cref="Action"/> containing a <see cref="ClientOptions"/> instance.</param>
/// <returns>A <see cref="IServiceCollection"/> instance.</returns>
public static IServiceCollection AddBlazorAuth0(this IServiceCollection services, Action<ClientOptions> options = null)
public static IServiceCollection AddBlazorAuth0(this IServiceCollection services, Action<ClientOptions> options)
{
services.AddBlazorAuth0ClientOptions(options);

Expand Down Expand Up @@ -65,6 +65,5 @@ public static IServiceCollection AddBlazorAuth0ClientOptions(this IServiceCollec
services.AddSingleton(resolver => options ?? resolver.GetRequiredService<IOptions<ClientOptions>>().Value);
return services;
}

}
}
Loading

0 comments on commit efc0e6a

Please sign in to comment.