public async Task <IActionResult> OnPostAsync() { try { if (!ModelState.IsValid) { string retorno = ClaimsService.ReadClaimsPrincipal(HttpContext.User, ClaimTypes.PrimarySid); Guid idRecurso = new(retorno); Lista = await _cpnucleoApiService.GetAsync <IEnumerable <ApontamentoViewModel> >("apontamento", "getbyrecurso", Token, idRecurso); ListaTarefas = await _cpnucleoApiService.GetAsync <IEnumerable <TarefaViewModel> >("tarefa", "getbyrecurso", Token, idRecurso); return(Page()); } await _cpnucleoApiService.PostAsync <ApontamentoViewModel>("apontamento", Token, Apontamento); return(RedirectToPage("Listar")); } catch (Exception ex) { ModelState.AddModelError(string.Empty, ex.Message); return(Page()); } }
// For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301883 public void ConfigureAuth(IAppBuilder app) { app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ExternalCookie, LoginPath = new PathString("/account/login"), LogoutPath = new PathString("/account/logout"), }); var claimsService = new ClaimsService(); foreach (var issuer in claimsService.Issuers) { var wsFederation = new WsFederationAuthenticationOptions { AuthenticationType = issuer.IssuerName, Caption = issuer.Name, MetadataAddress = issuer.MetadataUrl, Wtrealm = claimsService.CurrentRealm.RealmUri, TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false } }; app.UseWsFederationAuthentication(wsFederation); } app.SetDefaultSignInAsAuthenticationType(DefaultAuthenticationTypes.ExternalCookie); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { if (!ModelState.IsValid) { return(Page()); } RecursoViewModel recurso = await _recursoGrpcService.AutenticarAsync(Login.Usuario, Login.Senha); if (recurso.Id == Guid.Empty) { ModelState.AddModelError(string.Empty, "Usuário ou senha inválidos."); return(Page()); } IEnumerable <Claim> claims = new[] { new Claim(ClaimTypes.PrimarySid, recurso.Id.ToString()), }; ClaimsPrincipal principal = ClaimsService.CreateClaimsPrincipal(claims); await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTime.UtcNow.AddMinutes(_systemConfiguration.CookieExpires) }); return(RedirectToLocal(returnUrl)); }
public async Task <IActionResult> OnPostAsync() { try { if (!ModelState.IsValid) { string retorno = ClaimsService.ReadClaimsPrincipal(HttpContext.User, ClaimTypes.PrimarySid); Guid idRecurso = new Guid(retorno); Lista = await _apontamentoApiService.ListarPorRecursoAsync(Token, idRecurso); ListaTarefas = await _tarefaApiService.ListarPorRecursoAsync(Token, idRecurso); return(Page()); } await _apontamentoApiService.IncluirAsync(Token, Apontamento); return(RedirectToPage("Listar")); } catch (Exception ex) { ModelState.AddModelError(string.Empty, ex.Message); return(Page()); } }
public void GetClaims() { Claim mockClaimRecord = new Claim { ClaimId = 1, Title = "View Only", Description = "permission to view" }; Claim request = new Claim { ClaimId = 0, Title = "", Description = "" }; var mockClaimList = new List <Claim> { new Claim { ClaimId = 1, Title = "View Only", Description = "permission to view" } }; mockRepository.Setup(m => m.GetClaims(It.IsAny <Claim>())).Returns(mockClaimList); var mockClaimService = new ClaimsService(mockRepository.Object); var result = mockClaimService.GetClaims(request); Assert.AreEqual(1, result.Count()); Assert.AreEqual(result.FirstOrDefault().ClaimId, mockClaimRecord.ClaimId); Assert.AreEqual(result.FirstOrDefault().Title, mockClaimRecord.Title); Assert.AreEqual(result.FirstOrDefault().Description, mockClaimRecord.Description); mockClaimService.Should().NotBeNull(); }
public async void GenerateClaimsForIdentity_NoIssuer_ThrowException() { var expectedInvalidIssuer = TestHelper.GenerateRandomString(); var issuer = TestHelper.GenerateRandomString(); authenticateInfo = GenerateAuthenticateInfo(issuer, false); authenticateInfo.Properties.Items["scheme"] = FabricIdentityConstants.AuthenticationSchemes.Azure; AppConfiguration.AzureActiveDirectorySettings.IssuerWhiteList = new string[] { issuer = expectedInvalidIssuer }; Exception expectedException = null; try { var result = await ClaimsService.GenerateClaimsForIdentity(authenticateInfo, authorizationRequest); Assert.True(false, "The code should not call this line. It should have thrown an exception."); } catch (Exception exc) { expectedException = exc; } Assert.NotNull(expectedException); Assert.IsType <MissingIssuerClaimException>(expectedException); Assert.Equal <string>( ExceptionMessageResources.MissingIssuerClaimMessage, expectedException.Message); }
public string Login(LoginModelDTO model) { if (model is null) { throw new AccountException("Login model is null"); } var user = userManager.FindByEmailAsync(model.Email).Result; if (user != null && userManager.CheckPasswordAsync(user, model.Password).Result) { var roles = userManager.GetRolesAsync(user).Result; var claims = new ClaimsService().GetClaims(user, roles); if (claims != null) { var token = JWT_Service.GetToken(claims); return(token); } else { throw new AccountException("Claims are null"); } } else { throw new AccountException("Password was not confirmed"); } }
public async void GenerateClaimsForIdentity_HappyPathNonAzure_RemovesNameIdentitiferUserIdClaim() { authenticateInfo = GenerateAuthenticateInfo(null, true, false); var result = await ClaimsService.GenerateClaimsForIdentity(authenticateInfo, authorizationRequest); Assert.False(result.Claims.Any(x => x.Type == ClaimTypes.NameIdentifier)); }
public async void GenerateClaimsForIdentity_HappyPathNonAzure_RemovesSubjectUserIdClaim() { authenticateInfo = GenerateAuthenticateInfo(null, true, false); var result = await ClaimsService.GenerateClaimsForIdentity(authenticateInfo, authorizationRequest); Assert.DoesNotContain(result.Claims, x => x.Type == JwtClaimTypes.Subject); }
public ClaimsServiceTests() { var mockExternalIdentityProviderService = new Mock <IExternalIdentityProviderService>(); mockExternalIdentityProviderService.SetupFindUserBySubjectId(""); AppConfiguration = new AppConfiguration(); AppConfiguration.AzureActiveDirectorySettings = new AzureActiveDirectorySettings(); ClaimsService = new ClaimsService(AppConfiguration, mockExternalIdentityProviderService.Object); this.AppConfiguration.AzureAuthenticationEnabled = true; }
public async Task <IActionResult> OnGetAsync() { string retorno = ClaimsService.ReadClaimsPrincipal(HttpContext.User, ClaimTypes.PrimarySid); Guid idRecurso = new Guid(retorno); Lista = await _apontamentoGrpcService.ListarPorRecursoAsync(idRecurso); ListaTarefas = await _tarefaGrpcService.ListarPorRecursoAsync(idRecurso); return(Page()); }
public void GetEffectiveUserId_NonAzureADToken_ReturnsUserIdClaim() { var expectedUserId = TestHelper.GenerateRandomString(); this.AppConfiguration.AzureAuthenticationEnabled = false; claimResult.SchemeItem = "NotAzure"; claimResult.UserId = expectedUserId; var result = ClaimsService.GetEffectiveUserId(claimResult); Assert.Equal <string>(expectedUserId, result); }
public void AddClaim() { Claim request = new Claim { ClaimId = 0, Title = "Test", Description = "Test" }; mockRepository.Setup(m => m.AddClaim(It.IsAny <Claim>())).Returns(true); var mockClaimService = new ClaimsService(mockRepository.Object); var result = mockClaimService.AddClaim(request); mockClaimService.Should().NotBeNull(); Assert.AreEqual(true, result); }
public void DeleteClaimById() { ClaimViewModal mockClaimRecord = new ClaimViewModal { ClaimId = 2, Title = "View Only", Description = "permission to view" }; mockRepository.Setup(m => m.DeleteClaimById(It.IsAny <int>())).Returns(true); var mockClaimService = new ClaimsService(mockRepository.Object); var result = mockClaimService.DeleteClaimById(mockClaimRecord.ClaimId); mockClaimService.Should().NotBeNull(); Assert.AreEqual(true, result); }
public async void GenerateClaimsForIdentity_HappyPathAzure_ReturnsClaimsResult() { var issuer = TestHelper.GenerateRandomString(); authenticateInfo = GenerateAuthenticateInfo(issuer); authenticateInfo.Properties.Items["scheme"] = FabricIdentityConstants.AuthenticationSchemes.Azure; AppConfiguration.AzureActiveDirectorySettings.IssuerWhiteList = new string[] { issuer = "LOCAL AUTHORITY" }; var result = await ClaimsService.GenerateClaimsForIdentity(authenticateInfo, authorizationRequest); AssertClaimsResult(authenticateInfo, authorizationRequest, result); }
public void DeleteClaim() { Claim mockClaimRecord = new Claim { ClaimId = 2, Title = "View Only", Description = "permission to view" }; Claim request = mockClaimRecord; mockRepository.Setup(m => m.RemoveClaim(It.IsAny <Claim>())).Returns(true); var mockClaimService = new ClaimsService(mockRepository.Object); var result = mockClaimService.DeleteClaim(request); mockClaimService.Should().NotBeNull(); Assert.AreEqual(true, result); }
public async Task <IActionResult> OnPostAsync() { if (!ModelState.IsValid) { string retorno = ClaimsService.ReadClaimsPrincipal(HttpContext.User, ClaimTypes.PrimarySid); Guid idRecurso = new Guid(retorno); Lista = await _apontamentoGrpcService.ListarPorRecursoAsync(idRecurso); ListaTarefas = await _tarefaGrpcService.ListarPorRecursoAsync(idRecurso); return(Page()); } await _apontamentoGrpcService.IncluirAsync(Apontamento); return(RedirectToPage("Listar")); }
public void GetEffectiveSubjectId_NullClaimResult_ReturnsException() { Exception excResult = null; try { var result = ClaimsService.GetEffectiveSubjectId(null, new User()); Assert.True(false, "Should not get past this function call."); } catch (Exception exc) { excResult = exc; } Assert.NotNull(excResult); Assert.IsType <ArgumentNullException>(excResult); Assert.True(excResult.Message.Contains("The object name 'claimInformation' cannot be null.")); }
public void GetEffectiveSubjectId_NoAzureClaims_ReturnsUserSubjectId() { this.AppConfiguration.AzureAuthenticationEnabled = true; var expectedSubjectId = TestHelper.GenerateRandomString(); var claimSubjectId = TestHelper.GenerateRandomString(); claimResult.Claims = new List <Claim>() { }; user.SubjectId = expectedSubjectId; var result = ClaimsService.GetEffectiveSubjectId(claimResult, user); Assert.Equal <string>(expectedSubjectId, result); Assert.Equal <string>(expectedSubjectId, result); Assert.NotEqual <string>(claimSubjectId, result); }
public async void GenerateClaimsForIdentity_NullInfo_ReturnsException() { Exception excResult = null; try { var result = await ClaimsService.GenerateClaimsForIdentity(null, new AuthorizationRequest()); Assert.True(false, "Should not get past this function call."); } catch (Exception exc) { excResult = exc; } Assert.NotNull(excResult); Assert.IsType <ArgumentNullException>(excResult); Assert.True(excResult.Message.Contains("The object name 'info' cannot be null.")); }
protected void LogIn(object sender, EventArgs e) { var claimsService = new ClaimsService(); var issuer = claimsService.Issuers.FirstOrDefault(i => i.Name == ddlClaimsIssuer.SelectedItem.Text); if (issuer == null) { FailureText.Text = "Invalid issuer"; ErrorMessage.Visible = true; return; } AuthenticationManager.Challenge(new AuthenticationProperties { RedirectUri = Request.QueryString["ReturnUrl"] }, issuer.IssuerName); }
public void GetEffectiveSubjectId_OIDAzureClaim_ReturnsAzureSubjectId() { this.AppConfiguration.AzureAuthenticationEnabled = true; var expectedSubjectId = TestHelper.GenerateRandomString(); var claimSubjectId = TestHelper.GenerateRandomString(); claimResult.Claims = new List <Claim>() { new Claim(AzureActiveDirectoryJwtClaimTypes.OID, claimSubjectId) }; user.SubjectId = expectedSubjectId; var result = ClaimsService.GetEffectiveSubjectId(claimResult, user); Assert.Equal <string>(claimSubjectId, result); Assert.Equal <string>(claimSubjectId, result); Assert.NotEqual <string>(expectedSubjectId, result); }
public void GetEffectiveUserId_NoAzureClaims_ReturnsUserIdClaim() { this.AppConfiguration.AzureAuthenticationEnabled = true; var expectedUserId = TestHelper.GenerateRandomString(); var claimSubjectId = TestHelper.GenerateRandomString(); claimResult.SchemeItem = FabricIdentityConstants.AuthenticationSchemes.Azure; claimResult.Claims = new List <Claim>() { }; claimResult.UserId = expectedUserId; var result = ClaimsService.GetEffectiveUserId(claimResult); Assert.Equal <string>(expectedUserId, result); Assert.Equal <string>(expectedUserId, result); Assert.NotEqual <string>(claimSubjectId, result); }
public void GetEffectiveUserId_OIDAlternativeAzureClaim_ReturnsAzureSubjectId() { this.AppConfiguration.AzureAuthenticationEnabled = true; var expectedUserId = TestHelper.GenerateRandomString(); var claimSubjectId = TestHelper.GenerateRandomString(); claimResult.SchemeItem = FabricIdentityConstants.AuthenticationSchemes.Azure; claimResult.Claims = new List <Claim>() { new Claim(AzureActiveDirectoryJwtClaimTypes.OID_Alternative, claimSubjectId) }; claimResult.UserId = expectedUserId; var result = ClaimsService.GetEffectiveUserId(claimResult); Assert.Equal <string>(claimSubjectId, result); Assert.Equal <string>(claimSubjectId, result); Assert.NotEqual <string>(expectedUserId, result); }
public void GetEffectiveUserId_SchemeItemNotAzure_ReturnsUserIdClaim() { this.AppConfiguration.AzureAuthenticationEnabled = true; var expectedUserId = TestHelper.GenerateRandomString(); var claimSubjectId = TestHelper.GenerateRandomString(); claimResult.SchemeItem = "not azure"; claimResult.Claims = new List <Claim>() { new Claim(AzureActiveDirectoryJwtClaimTypes.OID_Alternative, claimSubjectId) }; claimResult.UserId = expectedUserId; var result = ClaimsService.GetEffectiveUserId(claimResult); Assert.Equal(expectedUserId, result); Assert.Equal(expectedUserId, result); Assert.NotEqual(claimSubjectId, result); }
public void GetEffectiveSubjectId_NullUser_ReturnsException() { var claimResult = new ClaimsResult() { SchemeItem = FabricIdentityConstants.AuthenticationSchemes.Azure }; Exception excResult = null; try { var result = ClaimsService.GetEffectiveSubjectId(claimResult, null); Assert.True(false, "Should not get past this function call."); } catch (Exception exc) { excResult = exc; } Assert.NotNull(excResult); Assert.IsType <ArgumentNullException>(excResult); Assert.True(excResult.Message.Contains("The object name 'user' cannot be null.")); }
public async Task <IActionResult> OnPostAsync(string?returnUrl = null) { try { if (!ModelState.IsValid) { return(Page()); } RecursoViewModel recurso = await _cpnucleoApiService.PostAsync <RecursoViewModel>("recurso", "auth", "", Auth); IEnumerable <Claim> claims = new[] { new Claim(ClaimTypes.PrimarySid, recurso.Id.ToString()), new Claim(ClaimTypes.Hash, recurso.Token) }; ClaimsPrincipal principal = ClaimsService.CreateClaimsPrincipal(claims); int.TryParse(_configuration["Cookie:Expires"], out int expiresUtc); await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTime.UtcNow.AddMinutes(expiresUtc) }); return(RedirectToLocal(returnUrl)); } catch (Exception ex) { ModelState.AddModelError(string.Empty, ex.Message); return(Page()); } }
public async void GenerateClaimsForIdentity_NoUserIdClaim_ThrowException() { authenticateInfo = GenerateAuthenticateInfo(null, true, false, false); Exception expectedException = null; try { var result = await ClaimsService.GenerateClaimsForIdentity(authenticateInfo, authorizationRequest); Assert.True(false, "The code should not call this line. It should have thrown an exception."); } catch (Exception exc) { expectedException = exc; } Assert.NotNull(expectedException); Assert.IsType <MissingUserClaimException>(expectedException); Assert.Equal <string>( ExceptionMessageResources.MissingUserClaimMessage, expectedException.Message); }
public IActionResult SignIn([FromServices] ClaimsService claimsService) { return(View(claimsService.Claims())); }
private async Task <int> OnExecuteAsync(CommandLineApplication app, CancellationToken cancellationToken = default) { RulesetsAndClaimPermissions input = JsonConvert.DeserializeObject <RulesetsAndClaimPermissions>( File.ReadAllText(this.FilePath)); ClaimsService claimsClient; if (string.IsNullOrEmpty(this.MarainClaimsHeaderRoleValue)) { var authenticationOptions = AuthenticationOptions.BuildFrom(this.UseAzCliDevAuth, this.TenantId); ServiceClientCredentials credentials = await authenticationOptions.GetServiceClientCredentialsFromKeyVault( this.ClaimsAppId, this.KeyVault, this.SecretName).ConfigureAwait(false); claimsClient = new ClaimsService(new Uri(this.ClaimsServiceUrl), credentials); } else { claimsClient = new ClaimsService(new Uri(this.ClaimsServiceUrl), new BasicAuthenticationCredentials()); claimsClient.HttpClient.DefaultRequestHeaders.Add("X-MARAIN-CLAIMS", $"{{ \"roles\": [ \"{this.MarainClaimsHeaderRoleValue}\" ] }}"); } using (claimsClient) { foreach (ResourceAccessRuleSet ruleSet in input.RuleSets) { try { app.Out.WriteLine($"Ruleset {ruleSet.Id} ('{ruleSet.DisplayName}')"); HttpOperationResponse <ResourceAccessRuleSet> result = await claimsClient.GetResourceAccessRuleSetWithHttpMessagesAsync( ruleSet.Id, this.MarainTenantId, cancellationToken : cancellationToken).ConfigureAwait(false); if (result.Response.StatusCode == HttpStatusCode.NotFound) { app.Error.WriteLine("Does not yet exist. Creating."); var request = new ResourceAccessRuleSet { Id = ruleSet.Id, DisplayName = ruleSet.DisplayName, Rules = ruleSet.Rules, }; await claimsClient.CreateResourceAccessRuleSetAsync( this.MarainTenantId, request, cancellationToken : cancellationToken).ConfigureAwait(false); } else if (result.Response.IsSuccessStatusCode) { app.Out.WriteLine("Already exists. Updating."); await claimsClient.SetResourceAccessRuleSetResourceAccessRulesAsync( this.MarainTenantId, ruleSet.Id, ruleSet.Rules, cancellationToken : cancellationToken).ConfigureAwait(false); } else { app.Error.WriteLine("Error: " + result.Response.StatusCode); string body = await result.Response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); if (!string.IsNullOrWhiteSpace(body)) { app.Error.WriteLine(body); } } } catch (Exception x) { app.Error.WriteLine(x); return(-1); } } foreach (CreateClaimPermissionsRequest claimPermissions in input.ClaimPermissions) { try { app.Out.WriteLine($"Claim Permissions {claimPermissions.Id}"); HttpOperationResponse <ClaimPermissions> result = await claimsClient.GetClaimPermissionsWithHttpMessagesAsync( claimPermissions.Id, this.MarainTenantId, cancellationToken : cancellationToken).ConfigureAwait(false); if (result.Response.StatusCode == HttpStatusCode.NotFound) { app.Out.WriteLine("Does not yet exist. Creating."); var request = new CreateClaimPermissionsRequest { Id = claimPermissions.Id, ResourceAccessRules = claimPermissions.ResourceAccessRules, ResourceAccessRuleSets = claimPermissions.ResourceAccessRuleSets, }; await claimsClient.CreateClaimPermissionsAsync( this.MarainTenantId, request, cancellationToken : cancellationToken).ConfigureAwait(false); } else if (result.Response.IsSuccessStatusCode) { app.Out.WriteLine("Already exists. Updating resource access rules."); await claimsClient.SetClaimPermissionsResourceAccessRulesAsync( this.MarainTenantId, claimPermissions.Id, claimPermissions.ResourceAccessRules, cancellationToken : cancellationToken).ConfigureAwait(false); app.Out.WriteLine("Updating resource access rule sets"); var ruleSetIds = claimPermissions .ResourceAccessRuleSets .Select(rs => new ResourceAccessRuleSetIdOnly(rs.Id)) .ToList(); await claimsClient.SetClaimPermissionsResourceAccessRuleSetsAsync( this.MarainTenantId, claimPermissions.Id, ruleSetIds, cancellationToken : cancellationToken).ConfigureAwait(false); } else { app.Error.WriteLine("Error: " + result.Response.StatusCode); string body = await result.Response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); if (!string.IsNullOrWhiteSpace(body)) { app.Error.WriteLine(body); } } } catch (Exception x) { app.Error.WriteLine(x); return(-1); } } } return(0); }