public async Task CanTwoFactorSignIn(bool isPersistent, bool supportsLockout, bool externalLogin, bool rememberClient) { // Setup var user = new PocoUser { UserName = "******" }; var manager = SetupUserManager(user); var provider = "twofactorprovider"; var code = "123456"; manager.Setup(m => m.SupportsUserLockout).Returns(supportsLockout).Verifiable(); if (supportsLockout) { manager.Setup(m => m.IsLockedOutAsync(user)).ReturnsAsync(false).Verifiable(); manager.Setup(m => m.ResetAccessFailedCountAsync(user)).ReturnsAsync(IdentityResult.Success).Verifiable(); } manager.Setup(m => m.VerifyTwoFactorTokenAsync(user, provider, code)).ReturnsAsync(true).Verifiable(); var context = new DefaultHttpContext(); var auth = MockAuth(context); var helper = SetupSignInManager(manager.Object, context); var twoFactorInfo = new SignInManager <PocoUser> .TwoFactorAuthenticationInfo { UserId = user.Id }; var loginProvider = "loginprovider"; var id = helper.StoreTwoFactorInfo(user.Id, externalLogin ? loginProvider : null); if (externalLogin) { auth.Setup(a => a.SignInAsync(context, IdentityConstants.ApplicationScheme, It.Is <ClaimsPrincipal>(i => i.FindFirstValue(ClaimTypes.AuthenticationMethod) == loginProvider && i.FindFirstValue("amr") == "mfa" && i.FindFirstValue(ClaimTypes.NameIdentifier) == user.Id), It.IsAny <AuthenticationProperties>())).Returns(Task.FromResult(0)).Verifiable(); // REVIEW: restore ability to test is persistent //It.Is<AuthenticationProperties>(v => v.IsPersistent == isPersistent))).Verifiable(); auth.Setup(a => a.SignOutAsync(context, IdentityConstants.ExternalScheme, It.IsAny <AuthenticationProperties>())).Returns(Task.FromResult(0)).Verifiable(); auth.Setup(a => a.SignOutAsync(context, IdentityConstants.TwoFactorUserIdScheme, It.IsAny <AuthenticationProperties>())).Returns(Task.FromResult(0)).Verifiable(); } else { SetupSignIn(context, auth, user.Id, isPersistent, null, "mfa"); } if (rememberClient) { auth.Setup(a => a.SignInAsync(context, IdentityConstants.TwoFactorRememberMeScheme, It.Is <ClaimsPrincipal>(i => i.FindFirstValue(ClaimTypes.Name) == user.Id && i.Identities.First().AuthenticationType == IdentityConstants.TwoFactorRememberMeScheme), It.IsAny <AuthenticationProperties>())).Returns(Task.FromResult(0)).Verifiable(); //It.Is<AuthenticationProperties>(v => v.IsPersistent == true))).Returns(Task.FromResult(0)).Verifiable(); } auth.Setup(a => a.AuthenticateAsync(context, IdentityConstants.TwoFactorUserIdScheme)) .ReturnsAsync(AuthenticateResult.Success(new AuthenticationTicket(id, null, IdentityConstants.TwoFactorUserIdScheme))).Verifiable(); // Act var result = await helper.TwoFactorSignInAsync(provider, code, isPersistent, rememberClient); // Assert Assert.True(result.Succeeded); manager.Verify(); auth.Verify(); }
protected override async Task <AuthenticateResult> HandleAuthenticateAsync() { var events = Events as BasicEvents; try { // .NET Core as of 2.0 does not support HTTP auth on sockets // This is alternative solution to anonymous access in SessionController.GetPipe() // but it only works for local connections (which may be OK for VSC but it won't work // in VSC with remote or Docker containers. //if (Uri.TryCreate(CurrentUri, UriKind.Absolute, out var uri)) { // if (uri.IsLoopback && !Request.IsHttps) { // var claims = new[] { // new Claim(ClaimTypes.Name, "RTVS"), // new Claim(Claims.RUser, string.Empty), // }; // var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, BasicDefaults.AuthenticationScheme)); // var t = new AuthenticationTicket(principal, new AuthenticationProperties(), Scheme.Name); // return AuthenticateResult.Success(t); // } //} // retrieve authorization header string authorization = Request.Headers[HeaderNames.Authorization]; if (string.IsNullOrEmpty(authorization)) { return(AuthenticateResult.NoResult()); } if (!authorization.StartsWith(RequestHeaderPrefix, StringComparison.OrdinalIgnoreCase)) { return(AuthenticateResult.NoResult()); } // retrieve credentials from header var encodedCredentials = authorization.Substring(RequestHeaderPrefix.Length); var decodedCredentials = default(string); try { decodedCredentials = Encoding.UTF8.GetString(Convert.FromBase64String(encodedCredentials)); } catch (Exception) { return(AuthenticateResult.Fail("Invalid basic authentication header encoding.")); } var index = decodedCredentials.IndexOf(':'); if (index == -1) { return(AuthenticateResult.Fail("Invalid basic authentication header format.")); } var username = decodedCredentials.Substring(0, index); var password = decodedCredentials.Substring(index + 1); var signInContext = new BasicSignInContext(Context, Scheme, Options) { Username = username, Password = password, }; await events.SignIn(signInContext); if (signInContext.Principal == null) { return(AuthenticateResult.Fail("Invalid basic authentication credentials.")); } var ticket = new AuthenticationTicket(signInContext.Principal, new AuthenticationProperties(), Scheme.Name); return(AuthenticateResult.Success(ticket)); } catch (Exception ex) { var authenticationFailedContext = new AuthenticationFailedContext(Context, Scheme, Options) { Exception = ex, }; await events.AuthenticationFailed(authenticationFailedContext); if (authenticationFailedContext.Result != null) { return(authenticationFailedContext.Result); } throw; } }
private AuthorizationFilterContext GetAuthorizationContext( bool anonymous = false, Action <IServiceCollection> registerServices = null) { var basicPrincipal = new ClaimsPrincipal( new ClaimsIdentity( new Claim[] { new Claim("Permission", "CanViewPage"), new Claim(ClaimTypes.Role, "Administrator"), new Claim(ClaimTypes.Role, "User"), new Claim(ClaimTypes.NameIdentifier, "John") }, "Basic")); var validUser = basicPrincipal; var bearerIdentity = new ClaimsIdentity( new Claim[] { new Claim("Permission", "CupBearer"), new Claim(ClaimTypes.Role, "Token"), new Claim(ClaimTypes.NameIdentifier, "John Bear") }, "Bearer"); var bearerPrincipal = new ClaimsPrincipal(bearerIdentity); validUser.AddIdentity(bearerIdentity); // ServiceProvider var serviceCollection = new ServiceCollection(); var auth = new Mock <IAuthenticationService>(); serviceCollection.AddOptions(); serviceCollection.AddLogging(); serviceCollection.AddSingleton(auth.Object); serviceCollection.AddAuthorization(); serviceCollection.AddAuthorizationPolicyEvaluator(); if (registerServices != null) { registerServices(serviceCollection); } var serviceProvider = serviceCollection.BuildServiceProvider(); // HttpContext var httpContext = new Mock <HttpContext>(); auth.Setup(c => c.AuthenticateAsync(httpContext.Object, "Bearer")).ReturnsAsync(AuthenticateResult.Success(new AuthenticationTicket(bearerPrincipal, "Bearer"))); auth.Setup(c => c.AuthenticateAsync(httpContext.Object, "Basic")).ReturnsAsync(AuthenticateResult.Success(new AuthenticationTicket(basicPrincipal, "Basic"))); auth.Setup(c => c.AuthenticateAsync(httpContext.Object, "Fails")).ReturnsAsync(AuthenticateResult.Fail("Fails")); httpContext.SetupProperty(c => c.User); if (!anonymous) { httpContext.Object.User = validUser; } httpContext.SetupGet(c => c.RequestServices).Returns(serviceProvider); // AuthorizationFilterContext var actionContext = new ActionContext( httpContext: httpContext.Object, routeData: new RouteData(), actionDescriptor: new ActionDescriptor()); var authorizationContext = new Filters.AuthorizationFilterContext( actionContext, Enumerable.Empty <IFilterMetadata>().ToList() ); return(authorizationContext); }
protected override Task <AuthenticateResult> HandleAuthenticateAsync() { var authenticationTicket = new AuthenticationTicket(_principal, new AuthenticationProperties(), "TEST"); return(Task.FromResult(AuthenticateResult.Success(authenticationTicket))); }
protected override async Task <AuthenticateResult> HandleAuthenticateAsync() { string authorizationHeader = Request.Headers["Authorization"]; if (string.IsNullOrEmpty(authorizationHeader)) { return(AuthenticateResult.NoResult()); } if (!authorizationHeader.StartsWith(_Scheme + ' ', StringComparison.OrdinalIgnoreCase)) { return(AuthenticateResult.NoResult()); } string encodedCredentials = authorizationHeader.Substring(_Scheme.Length).Trim(); if (string.IsNullOrEmpty(encodedCredentials)) { const string noCredentialsMessage = "No credentials"; Logger.LogInformation(noCredentialsMessage); return(AuthenticateResult.Fail(noCredentialsMessage)); } try { string decodedCredentials = string.Empty; try { decodedCredentials = Encoding.UTF8.GetString(Convert.FromBase64String(encodedCredentials)); } catch (Exception ex) { throw new Exception($"Failed to decode credentials : {encodedCredentials}", ex); } var delimiterIndex = decodedCredentials.IndexOf(':'); if (delimiterIndex == -1) { const string missingDelimiterMessage = "Invalid credentials, missing delimiter."; Logger.LogInformation(missingDelimiterMessage); return(AuthenticateResult.Fail(missingDelimiterMessage)); } var username = decodedCredentials.Substring(0, delimiterIndex); var password = decodedCredentials.Substring(delimiterIndex + 1); var validateCredentialsContext = new ValidateCredentialsContext(Context, Scheme, Options) { Username = username, Password = password }; await Options.Events.ValidateCredentials(validateCredentialsContext); if (validateCredentialsContext.Result != null) { var ticket = new AuthenticationTicket(validateCredentialsContext.Principal, Scheme.Name); return(AuthenticateResult.Success(ticket)); } return(AuthenticateResult.NoResult()); } catch (Exception ex) { var authenticationFailedContext = new AuthenticationFailedContext(Context, Scheme, Options) { Exception = ex }; await Options.Events.AuthenticationFailed(authenticationFailedContext); if (authenticationFailedContext.Result.Succeeded) { return(AuthenticateResult.Success(authenticationFailedContext.Result.Ticket)); } if (authenticationFailedContext.Result.None) { return(AuthenticateResult.NoResult()); } throw; } }
protected override async Task <AuthenticateResult> HandleAuthenticateAsync() { if (!Request.Headers.ContainsKey("Authorization")) { return(AuthenticateResult.Fail("Missing Authorization Header")); } EmployeeModel admin = null; ClientModel client = null; LoginData loginDataPerson = null; Person person = null; try { var authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]); var credentialBytes = Convert.FromBase64String(authHeader.Parameter); var credentials = Encoding.UTF8.GetString(credentialBytes).Split(':'); var username = credentials[0]; var password = credentials[1]; admin = _adminService.AuthenticateEmployee(username, password); client = _clientService.AuthenticateClient(username, password); loginDataPerson = _context.LoginData.FirstOrDefault(x => x.Username == username); person = _context.People.FirstOrDefault(x => x.LoginDataId == loginDataPerson.LoginDataId); } catch { return(AuthenticateResult.Fail("Invalid Authorization Header")); } if (admin == null && client == null) { return(AuthenticateResult.Fail("Invalid Username or Password")); } var claims = new List <Claim> { new Claim(ClaimTypes.NameIdentifier, loginDataPerson.Username), new Claim(ClaimTypes.Name, person.FirstName), }; if (admin != null) { var employeeRoles = _context.EmployeeRoles.ToList(); var employeeRolesList = _context.EmployeeEmployeeRoles.ToList(); foreach (var x in employeeRolesList) { if (admin.EmployeeId == x.EmployeeId) { foreach (var y in employeeRoles) { if (x.EmployeeRolesId == y.EmployeeRolesId) { claims.Add(new Claim(ClaimTypes.Role, y.Name)); } } break; } } } if (client != null) { claims.Add(new Claim(ClaimTypes.Role, "Client")); } var identity = new ClaimsIdentity(claims, Scheme.Name); var principal = new ClaimsPrincipal(identity); var ticket = new AuthenticationTicket(principal, Scheme.Name); return(AuthenticateResult.Success(ticket)); }
protected override async Task <AuthenticateResult> HandleAuthenticateAsync() { async Task <AuthenticateResult> DeleteLongSessionAndLogout(long sessionId) { await userManager.DeleteLongSessionAsync(sessionId); jweService.MakeLogoutCookiesAndHeaders(Response); return(AuthenticateResult.NoResult()); } AuthenticateResult Logout(string msg) { jweService.MakeLogoutCookiesAndHeaders(Response); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"\nLogout: {msg}\n"); Console.ResetColor(); return(AuthenticateResult.NoResult()); } try { var cookie = Request.Cookies[TokenClaimNames.LongToken2CoockiName]; if (cookie == null) { return(AuthenticateResult.NoResult()); } JwtSecurityToken jwtLongToken2 = jweService.ReadLong2Token(cookie); if (jwtLongToken2 == null) { return(Logout("No Long2 cookie token")); } var longToken2db = jwtLongToken2.Claims.First(x => x.Type == TokenClaimNames.LongToken2Db).Value; SunClaimsPrincipal sunClaimsPrincipal; if (Request.Headers.TryGetValue(Headers.LongToken1HeaderName, out StringValues longToken1db)) { int userId = int.Parse(jwtLongToken2.Claims.First(x => x.Type == ClaimTypes.NameIdentifier).Value); var longSessionToFind = new LongSession { UserId = userId, LongToken1 = longToken1db, LongToken2 = longToken2db }; var longSession = await userManager.FindLongSessionAsync(longSessionToFind); if (longSession == null) { return(Logout("Session not found")); } sunClaimsPrincipal = await jweService.RenewSecurityTokensAsync(Context, userId, longSession); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("\nToken renews\n"); Console.ResetColor(); } else { string authorization = Request.Headers["Authorization"]; if (string.IsNullOrEmpty(authorization)) { return(Logout("No Authorization header")); } string jwtShortToken = null; if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) { jwtShortToken = authorization.Substring("Bearer ".Length).Trim(); } if (string.IsNullOrEmpty(jwtShortToken)) { return(Logout("No Bearer in Authorization header")); } var claimsPrincipal = jweService.ReadShortToken(jwtShortToken); string lat2ran_1 = jwtLongToken2.Claims.First(x => x.Type == TokenClaimNames.LongToken2Ran).Value; string lat2ran_2 = claimsPrincipal.Claims.First(x => x.Type == TokenClaimNames.LongToken2Ran).Value; long sessionId = long.Parse(jwtLongToken2.Claims.First(x => x.Type == TokenClaimNames.SessionId).Value); if (!string.Equals(lat2ran_1, lat2ran_2)) { return(await DeleteLongSessionAndLogout(sessionId)); } string lat2db = jwtLongToken2.Claims.First(x => x.Type == TokenClaimNames.LongToken2Db).Value; sunClaimsPrincipal = new SunClaimsPrincipal(claimsPrincipal, rolesCache, sessionId, lat2db); } if (jweBlackListService.IsTokenInBlackList(sunClaimsPrincipal.LongToken2Db)) { return(await DeleteLongSessionAndLogout(sunClaimsPrincipal.SessionId)); } if (sunClaimsPrincipal.Roles.ContainsKey(RoleNames.Banned)) { return(await DeleteLongSessionAndLogout(sunClaimsPrincipal.SessionId)); } var authenticationTicket = new AuthenticationTicket(sunClaimsPrincipal, SunJwt.Scheme); return(AuthenticateResult.Success(authenticationTicket)); } catch (Exception e) { return(Logout("Error " + e)); } }
public Task <AuthenticateResult> AuthenticateAsync(HttpContext context, string scheme) { Principal = new ClaimsPrincipal(new ClaimsIdentity(scheme)); return(Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(Principal, scheme)))); }
protected override Task <AuthenticateResult> HandleAuthenticateAsync() { //We are expecting a header such as Authorization: <Schema> <key> //If this is not present, we will return NoResult and move on to the next authentication handler. if (!Request.Headers.TryGetValue(HeaderNames.Authorization, out StringValues values) || !values.Any()) { return(Task.FromResult(AuthenticateResult.NoResult())); } if (!AuthenticationHeaderValue.TryParse(values.First(), out AuthenticationHeaderValue authHeader)) { return(Task.FromResult(AuthenticateResult.Fail("Invalid authentication header"))); } if (!string.Equals(authHeader.Scheme, Scheme.Name, StringComparison.OrdinalIgnoreCase)) { return(Task.FromResult(AuthenticateResult.NoResult())); } //The user is passing a base 64-encoded version of the secret //We will be hash this and compare it to the secret in our configuration. byte[] secret = new byte[32]; Span <byte> span = new Span <byte>(secret); if (!Convert.TryFromBase64String(authHeader.Parameter, span, out int bytesWritten) || bytesWritten < 32) { return(Task.FromResult(AuthenticateResult.Fail("Invalid Api Key format"))); } //HACK IOptionsMonitor and similiar do not properly update here even though the underlying //configuration is updated. We get the value directly from IConfiguration. var authenticationOptions = new ApiAuthenticationOptions(); IConfiguration configService = Context.RequestServices.GetRequiredService <IConfiguration>(); configService.Bind(ApiAuthenticationOptions.ConfigurationKey, authenticationOptions); string apiKeyHash = authenticationOptions.ApiKeyHash; if (apiKeyHash == null) { return(Task.FromResult(AuthenticateResult.Fail("Server does not contain Api Key"))); } if (string.IsNullOrEmpty(authenticationOptions.ApiKeyHashType)) { return(Task.FromResult(AuthenticateResult.Fail("Missing hash algorithm"))); } if (DisallowedHashAlgorithms.Contains(authenticationOptions.ApiKeyHashType, StringComparer.OrdinalIgnoreCase)) { return(Task.FromResult(AuthenticateResult.Fail($"Disallowed hash algorithm {authenticationOptions.ApiKeyHashType}"))); } using HashAlgorithm algorithm = HashAlgorithm.Create(authenticationOptions.ApiKeyHashType); if (algorithm == null) { return(Task.FromResult(AuthenticateResult.Fail($"Invalid hash algorithm {authenticationOptions.ApiKeyHashType}"))); } byte[] hashedSecret = algorithm.ComputeHash(secret); //ApiKeyHash is represented as a hex string. e.g. AABBCCDDEEFF byte[] apiKeyHashBytes = new byte[apiKeyHash.Length / 2]; for (int i = 0; i < apiKeyHash.Length; i += 2) { if (!byte.TryParse(apiKeyHash.AsSpan(i, 2), NumberStyles.HexNumber, provider: NumberFormatInfo.InvariantInfo, result: out byte resultByte)) { return(Task.FromResult(AuthenticateResult.Fail("Invalid Api Key hash"))); } apiKeyHashBytes[i / 2] = resultByte; } if (hashedSecret.SequenceEqual(apiKeyHashBytes)) { return(Task.FromResult(AuthenticateResult.Success( new AuthenticationTicket( new ClaimsPrincipal(new[] { new ClaimsIdentity(AuthConstants.ApiKeySchema) }), AuthConstants.ApiKeySchema)))); } else { return(Task.FromResult(AuthenticateResult.Fail("Invalid Api Key"))); } }
protected override Task <AuthenticateResult> HandleAuthenticateAsync() => Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(Context.User, NoOpSchema)));
protected override async Task <AuthenticateResult> HandleAuthenticateAsync() { var cookieContainer = new CookieContainer(); var handler = new HttpClientHandler { CookieContainer = cookieContainer }; var uriString = $"{Context.Request.Scheme}://{Context.Request.Host}"; foreach (var cookie in Context.Request.Cookies) { cookieContainer.Add(new Uri(uriString), new Cookie(cookie.Key, cookie.Value)); } var request = new HttpRequestMessage(HttpMethod.Get, $"{uriString}/.auth/me"); foreach (var header in Context.Request.Headers) { if (header.Key.StartsWith("X-ZUMO-")) { request.Headers.Add(header.Key, header.Value[0]); } } JArray payload = null; using (HttpClient client = new HttpClient(handler)) { try { var response = await client.SendAsync(request); if (!response.IsSuccessStatusCode) { return(AuthenticateResult.Fail("Unable to fetch user information from auth endpoint.")); } var content = await response.Content.ReadAsStringAsync(); payload = JArray.Parse(content); } catch (Exception ex) { Logger.LogError(ex.Message); } } if (payload == null) { return(AuthenticateResult.Fail("Could not retrieve JSON from /me endpoint")); } var id = payload[0]["user_id"].Value <string>(); var idToken = payload[0]["id_token"].Value <string>(); var providerName = payload[0]["provider_name"].Value <string>(); Logger.LogDebug("payload was fetched from endpoint. id: {0}", id); var identity = new GenericIdentity(id); Logger.LogInformation("building claims from payload..."); List <Claim> claims = new List <Claim>(); foreach (var claim in payload[0]["user_claims"]) { claims.Add(new Claim(claim["typ"].ToString(), claim["val"].ToString())); } Logger.LogInformation("Add claims to new identity"); identity.AddClaims(claims); identity.AddClaim(new Claim("id_token", idToken)); identity.AddClaim(new Claim("provider_name", providerName)); ClaimsPrincipal p = new GenericPrincipal(identity, null); //todo add roles? var ticket = new AuthenticationTicket(p, new AuthenticationProperties(), Scheme.Name); Logger.LogInformation("Set identity to user context object."); this.Context.User = p; Logger.LogInformation("identity build was a success, returning ticket"); return(AuthenticateResult.Success(ticket)); }
protected override async Task <AuthenticateResult> HandleAuthenticateAsync() { if (!Request.Headers.ContainsKey(AuthorizationHeaderName)) { //Authorization header not in request return(AuthenticateResult.NoResult()); } if (!AuthenticationHeaderValue.TryParse(Request.Headers[AuthorizationHeaderName], out AuthenticationHeaderValue headerValue)) { //Invalid Authorization header return(AuthenticateResult.NoResult()); } if (!BasicSchemeName.Equals(headerValue.Scheme, StringComparison.OrdinalIgnoreCase)) { //Not Basic authentication header return(AuthenticateResult.NoResult()); } try { if (string.IsNullOrEmpty(headerValue.Parameter)) { return(AuthenticateResult.Fail(new Abp.UI.UserFriendlyException((int)Split.Dto.ResultCode.Auth_InvalidToken, "Invalid token"))); } byte[] headerValueBytes = Convert.FromBase64String(headerValue.Parameter); string userAndPassword = Encoding.UTF8.GetString(headerValueBytes); string[] parts = userAndPassword.Split(':'); if (parts.Length != 2) { return(AuthenticateResult.Fail(new Abp.UI.UserFriendlyException((int)Split.Dto.ResultCode.Auth_InvalidAutheHeader, "Invalid Basic authentication header"))); } string tenancyName = parts[0]; string apiKey = parts[1]; string userId = ""; string tenantId = ""; if (!string.IsNullOrEmpty(tenancyName)) { var tenants = await _tenantRepository.GetAll().IgnoreQueryFilters() .Where(o => o.ApiKey == apiKey && o.TenancyName == tenancyName && !o.IsDeleted && o.IsActive).ToListAsync(); if (tenants.Count == 0) { return(AuthenticateResult.Fail(new Abp.UI.UserFriendlyException((int)Split.Dto.ResultCode.Auth_InvalidInput, "Invalid tenancyname or apikey"))); } if (!tenants[0].IsActive) { return(AuthenticateResult.Fail(new Abp.UI.UserFriendlyException((int)Split.Dto.ResultCode.Auth_RefuseAuthorization, "tenant is banish"))); } var user = await this._userRepository.GetAll().IgnoreQueryFilters().SingleAsync(o => o.UserName == "admin" && o.TenantId == tenants[0].Id); tenantId = tenants[0].Id.ToString(); userId = user.Id.ToString(); } else if (apiKey.Equals(Options.SystemApiKey)) { var user = await this._userRepository.GetAll().IgnoreQueryFilters().SingleAsync(o => o.UserName == "admin" && o.TenantId == null); userId = user.Id.ToString(); } else { return(AuthenticateResult.Fail(new Abp.UI.UserFriendlyException((int)Split.Dto.ResultCode.Auth_InvalidInput, "Invalid tenancyname or apikey"))); } var claims = new[] { new Claim(ClaimTypes.NameIdentifier, userId), new Claim(AbpClaimTypes.TenantId, tenantId), new Claim(AbpClaimTypes.UserName, StaticRoleNames.Host.Admin) }; var identity = new ClaimsIdentity(claims, Scheme.Name); var principal = new ClaimsPrincipal(identity); var ticket = new AuthenticationTicket(principal, Scheme.Name); return(AuthenticateResult.Success(ticket)); } catch (Exception ex) when(ex is FormatException || ex is DecoderFallbackException) { return(AuthenticateResult.Fail(new Abp.UI.UserFriendlyException((int)Split.Dto.ResultCode.Auth_InvalidToken, "Invalid token"))); } catch (Exception ex) { LogHelper.Logger.Error("basic auth", ex); return(AuthenticateResult.Fail(new Abp.UI.UserFriendlyException((int)Split.Dto.ResultCode.SytemError, "Invalid auth request"))); } }
protected override async Task <AuthenticateResult> HandleAuthenticateAsync() { string siteMinderUserGuidHeader = Request.Headers["SMGOV_USERGUID"]; string siteMinderUserTypeHeader = Request.Headers["SMGOV_USERTYPE"]; if (siteMinderUserGuidHeader == null || siteMinderUserTypeHeader == null) { return(AuthenticateResult.NoResult()); } if (siteMinderUserTypeHeader != ValidSiteMinderUserType) { return(AuthenticateResult.Fail("Invalid SiteMinder UserType Header.")); } var authenticatedBySiteMinderPreviously = Context.User.Identity.AuthenticationType == SiteMinder; var applicationCode = Context.User.ApplicationCode(); var participantId = Context.User.ParticipantId(); var agencyCode = Context.User.AgencyCode(); var isSupremeUser = Context.User.IsSupremeUser(); if (!authenticatedBySiteMinderPreviously) { var request = new UserInfoRequest { DeviceName = Environment.MachineName, DomainUserGuid = siteMinderUserGuidHeader, DomainUserId = Request.Headers["SM_USER"], IpAddress = Request.Headers["X-Real-IP"], TemporaryAccessGuid = "" }; var jcUserInfo = await JCUserService.GetUserInfo(request); if (jcUserInfo == null) { return(AuthenticateResult.Fail("Couldn't authenticate through JC-Interface.")); } applicationCode = "SCV"; participantId = jcUserInfo.UserPartId; agencyCode = jcUserInfo.UserDefaultAgencyCd; isSupremeUser = true; } var claims = new[] { new Claim(CustomClaimTypes.ApplicationCode, applicationCode), new Claim(CustomClaimTypes.JcParticipantId, participantId), new Claim(CustomClaimTypes.JcAgencyCode, agencyCode), new Claim(CustomClaimTypes.IsSupremeUser, isSupremeUser.ToString()) }; var identity = new ClaimsIdentity(claims, Scheme.Name); var principal = new ClaimsPrincipal(identity); if (!authenticatedBySiteMinderPreviously) { await Context.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal); } var ticket = new AuthenticationTicket(principal, Scheme.Name); return(AuthenticateResult.Success(ticket)); }
protected override async Task <AuthenticateResult> HandleAuthenticateAsync() { bool isTokenFromCookie = false; try { Logger.LogDebug("HandleAuthenticateAsync: started authentication check..."); string token = string.Empty; // check first for header if (!string.IsNullOrEmpty(Program.JwtHeader)) { var header = Request.Headers["Authorization"]; if (header.Count() > 0) { Logger.LogDebug($"HandleAuthenticateAsync: checking header named \"Authorization\" for token..."); token = header.First().Replace("Bearer ", ""); } } // look next at the cookie if (!string.IsNullOrEmpty(Program.JwtCookie)) { Logger.LogDebug($"HandleAuthenticateAsync: checking cookie named \"{Program.JwtCookie}\" for token..."); token = Request.Cookies[Program.JwtCookie]; isTokenFromCookie = true; } // shortcut if there is no token if (string.IsNullOrEmpty(token)) { Logger.LogDebug("HandleAuthenticateAsync: no token was found."); return(AuthenticateResult.NoResult()); } // validate the token var jwt = await TokenValidator.ValidateToken(token); // propogate the claims (this overload uses uri-names and dedupes) var claims = new List <Claim>(); foreach (var claim in jwt.Payload.Claims) { claims.AddLong(claim.Type, claim.Value); } // build the identity, principal, and ticket var identity = new ClaimsIdentity(claims, Scheme.Name); var principal = new ClaimsPrincipal(identity); var ticket = new AuthenticationTicket(principal, Scheme.Name); return(AuthenticateResult.Success(ticket)); } catch (Exception e) { Logger.LogWarning(e, "HandleAuthenticateAsync: exception..."); if (isTokenFromCookie) { Response.Cookies.Delete(Program.JwtCookie); // revoke the cookie } return(AuthenticateResult.Fail(e)); } }
protected override Task <AuthenticateResult> HandleAuthenticateAsync() { return(Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "bob") })), new AuthenticationProperties(), "apikey")))); }
protected override Task <AuthenticateResult> HandleAuthenticateAsync() { var authenticationTicket = new AuthenticationTicket(new ClaimsPrincipal(this.Options.Identity(this.Request)), new AuthenticationProperties(), TestAuthenticationExtensions.TEST_AUTH_SCHEME); return(Task.FromResult(AuthenticateResult.Success(authenticationTicket))); }
protected override async Task <AuthenticateResult> HandleAuthenticateAsync() { if (!Request.Headers.ContainsKey("Authorization")) { return(AuthenticateResult.Fail("Missing Authorization Header")); } //Model.Korisnici user = null; var context = ""; try { context = Request.Headers["Context"]; var authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]); var credentialBytes = Convert.FromBase64String(authHeader.Parameter); var credentials = Encoding.UTF8.GetString(credentialBytes).Split(':'); var username = credentials[0]; var password = credentials[1]; if ("Registracija".Equals(context)) { RegistrovaniKorisnik = _userService.LoginMobile(new Model.Requests.KorisniciLoginRequest()//dodaj await { Username = username, Password = password }); } else { PrijavljeniKorisnik = _userService.Login( //dodaj await new Model.Requests.KorisniciLoginRequest() { Username = username, Password = password }); //Authenticiraj(username, password); } } catch { return(AuthenticateResult.Fail("Invalid Authorization Header")); } var claims = new List <Claim>(); if ("Registracija".Equals(context)) { if (RegistrovaniKorisnik == null) { return(AuthenticateResult.Fail("Invalid Username or Password")); } } else { if (PrijavljeniKorisnik == null) { return(AuthenticateResult.Fail("Invalid Username or Password")); } } claims = new List <Claim> { new Claim(ClaimTypes.NameIdentifier, PrijavljeniKorisnik.KorisnickoIme), new Claim(ClaimTypes.Name, PrijavljeniKorisnik.Ime), }; claims.Add(new Claim(ClaimTypes.Role, PrijavljeniKorisnik.Uloga.Naziv)); var identity = new ClaimsIdentity(claims, Scheme.Name); var principal = new ClaimsPrincipal(identity); var ticket = new AuthenticationTicket(principal, Scheme.Name); return(AuthenticateResult.Success(ticket)); }
protected override Task <AuthenticateResult> HandleAuthenticateAsync() => Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(_id, "Api")));
/// <summary> /// Process Authentication Request /// </summary> /// <returns></returns> protected override async Task <AuthenticateResult> HandleAuthenticateAsync() { // get siteminder headers _logger.LogDebug("Parsing the HTTP headers for SiteMinder authentication credential"); SiteMinderAuthOptions options = new SiteMinderAuthOptions(); bool isDeveloperLogin = false; bool isBCSCDeveloperLogin = false; try { ClaimsPrincipal principal; HttpContext context = Request.HttpContext; IDynamicsClient _dynamicsClient = (IDynamicsClient)context.RequestServices.GetService(typeof(IDynamicsClient)); IHostingEnvironment hostingEnv = (IHostingEnvironment)context.RequestServices.GetService(typeof(IHostingEnvironment)); UserSettings userSettings = new UserSettings(); string userId = null; string devCompanyId = null; string siteMinderGuid = ""; string siteMinderBusinessGuid = ""; string siteMinderUserType = ""; // ************************************************** // If this is an Error or Authentiation API - Ignore // ************************************************** string url = context.Request.GetDisplayUrl().ToLower(); if (url.Contains(".js")) { return(AuthenticateResult.NoResult()); } // ************************************************** // Check if we have a Dev Environment Cookie // ************************************************** //if (!hostingEnv.IsProduction()) //{ // check for a fake BCeID login in dev mode string temp = context.Request.Cookies[options.DevAuthenticationTokenKey]; if (string.IsNullOrEmpty(temp)) // could be an automated test user. { temp = context.Request.Headers["DEV-USER"]; } if (!string.IsNullOrEmpty(temp)) { if (temp.Contains("::")) { var temp2 = temp.Split("::"); userId = temp2[0]; if (temp2.Length >= 2) { devCompanyId = temp2[1]; } else { devCompanyId = temp2[0]; } } else { userId = temp; devCompanyId = temp; } isDeveloperLogin = true; _logger.LogDebug("Got user from dev cookie = " + userId + ", company = " + devCompanyId); } else { // same set of tests for a BC Services Card dev login temp = context.Request.Cookies[options.DevBCSCAuthenticationTokenKey]; if (string.IsNullOrEmpty(temp)) // could be an automated test user. { temp = context.Request.Headers["DEV-BCSC-USER"]; } if (!string.IsNullOrEmpty(temp)) { userId = temp; isBCSCDeveloperLogin = true; _logger.LogDebug("Got user from dev cookie = " + userId); } } //} // ************************************************** // Check if the user session is already created // ************************************************** try { _logger.LogInformation("Checking user session"); userSettings = UserSettings.ReadUserSettings(context); _logger.LogDebug("UserSettings found: " + userSettings.GetJson()); } catch { //do nothing _logger.LogDebug("No UserSettings found"); } // is user authenticated - if so we're done if ((userSettings.UserAuthenticated && string.IsNullOrEmpty(userId)) || (userSettings.UserAuthenticated && !string.IsNullOrEmpty(userId) && !string.IsNullOrEmpty(userSettings.UserId) && userSettings.UserId == userId)) { _logger.LogDebug("User already authenticated with active session: " + userSettings.UserId); principal = userSettings.AuthenticatedUser.ToClaimsPrincipal(options.Scheme, userSettings.UserType); return(AuthenticateResult.Success(new AuthenticationTicket(principal, null, Options.Scheme))); } string smgov_userdisplayname = context.Request.Headers["smgov_userdisplayname"]; if (!string.IsNullOrEmpty(smgov_userdisplayname)) { userSettings.UserDisplayName = smgov_userdisplayname; } string smgov_businesslegalname = context.Request.Headers["smgov_businesslegalname"]; if (!string.IsNullOrEmpty(smgov_businesslegalname)) { userSettings.BusinessLegalName = smgov_businesslegalname; } // ************************************************** // Authenticate based on SiteMinder Headers // ************************************************** _logger.LogDebug("Parsing the HTTP headers for SiteMinder authentication credential"); // At this point userID would only be set if we are logging in through as a DEV user if (string.IsNullOrEmpty(userId)) { _logger.LogDebug("Getting user data from headers"); userId = context.Request.Headers[options.SiteMinderUserNameKey]; if (string.IsNullOrEmpty(userId)) { userId = context.Request.Headers[options.SiteMinderUniversalIdKey]; } siteMinderGuid = context.Request.Headers[options.SiteMinderUserGuidKey]; siteMinderBusinessGuid = context.Request.Headers[options.SiteMinderBusinessGuidKey]; siteMinderUserType = context.Request.Headers[options.SiteMinderUserTypeKey]; // ************************************************** // Validate credentials // ************************************************** if (string.IsNullOrEmpty(userId)) { _logger.LogDebug(options.MissingSiteMinderUserIdError); return(AuthenticateResult.Fail(options.MissingSiteMinderGuidError)); } if (string.IsNullOrEmpty(siteMinderGuid)) { _logger.LogDebug(options.MissingSiteMinderGuidError); return(AuthenticateResult.Fail(options.MissingSiteMinderGuidError)); } if (string.IsNullOrEmpty(siteMinderUserType)) { _logger.LogDebug(options.MissingSiteMinderUserTypeError); return(AuthenticateResult.Fail(options.MissingSiteMinderUserTypeError)); } } else // DEV user, setup a fake session and SiteMinder headers. { if (isDeveloperLogin && _dynamicsClient != null) { _logger.LogError("Generating a Development user"); userSettings.BusinessLegalName = devCompanyId + " BusinessProfileName"; userSettings.UserDisplayName = userId + " BCeIDContactType"; // search for a matching user. var existingContact = _dynamicsClient.GetContactByName(userId, "BCeIDContactType"); if (existingContact != null) { siteMinderGuid = existingContact.Externaluseridentifier; } else { siteMinderGuid = GuidUtility.CreateIdForDynamics("contact", userSettings.UserDisplayName).ToString(); } var existingBusiness = await _dynamicsClient.GetAccountByLegalName(userSettings.BusinessLegalName); if (existingBusiness != null) { siteMinderBusinessGuid = existingBusiness.BcgovBceid; } { siteMinderBusinessGuid = GuidUtility.CreateIdForDynamics("account", userSettings.BusinessLegalName).ToString(); } siteMinderUserType = "Business"; } else if (isBCSCDeveloperLogin) { _logger.LogError("Generating a Development BC Services user"); userSettings.BusinessLegalName = null; userSettings.UserDisplayName = userId + " Associate"; siteMinderGuid = GuidUtility.CreateIdForDynamics("bcsc", userSettings.UserDisplayName).ToString(); siteMinderBusinessGuid = null; siteMinderUserType = "VerifiedIndividual"; } } // Previously the code would do a database lookup here. However there is no backing database for the users table now, // so we just do a Dynamics lookup on the siteMinderGuid. _logger.LogDebug("Loading user external id = " + siteMinderGuid); if (_dynamicsClient != null) { userSettings.AuthenticatedUser = await _dynamicsClient.LoadUser(siteMinderGuid, context.Request.Headers, _logger); } _logger.LogDebug("After getting authenticated user = "******" (" + userId + ")"); return(AuthenticateResult.Fail(options.InactivegDbUserIdError)); } if (userSettings.AuthenticatedUser != null && !String.IsNullOrEmpty(siteMinderUserType)) { userSettings.AuthenticatedUser.UserType = siteMinderUserType; } userSettings.UserType = siteMinderUserType; // This line gets the various claims for the current user. ClaimsPrincipal userPrincipal = userSettings.AuthenticatedUser.ToClaimsPrincipal(options.Scheme, userSettings.UserType); // ************************************************** // Create authenticated user // ************************************************** _logger.LogDebug("Authentication successful: " + userId); _logger.LogDebug("Setting identity and creating session for: " + userId); // create session info for the current user userSettings.UserId = userId; userSettings.UserAuthenticated = true; userSettings.IsNewUserRegistration = (userSettings.AuthenticatedUser == null); // set other session info userSettings.SiteMinderGuid = siteMinderGuid; userSettings.SiteMinderBusinessGuid = siteMinderBusinessGuid; _logger.LogDebug("Before getting contact and account ids = " + userSettings.GetJson()); if (userSettings.AuthenticatedUser != null) { userSettings.ContactId = userSettings.AuthenticatedUser.ContactId.ToString(); if (siteMinderBusinessGuid != null) // BCeID user { var account = await _dynamicsClient.GetAccountBySiteminderBusinessGuid(siteMinderBusinessGuid); if (account != null && account.Accountid != null) { userSettings.AccountId = account.Accountid; userSettings.AuthenticatedUser.AccountId = Guid.Parse(account.Accountid); } } } if (!hostingEnv.IsProduction() && (isDeveloperLogin || isBCSCDeveloperLogin)) { _logger.LogError("DEV MODE Setting identity and creating session for: " + userId); if (isDeveloperLogin) { userSettings.BusinessLegalName = devCompanyId + " BusinessProfileName"; userSettings.UserDisplayName = userId + " BCeIDContactType"; // add generated guids userSettings.SiteMinderBusinessGuid = GuidUtility.CreateIdForDynamics("account", userSettings.BusinessLegalName).ToString(); userSettings.SiteMinderGuid = GuidUtility.CreateIdForDynamics("contact", userSettings.UserDisplayName).ToString(); } else if (isBCSCDeveloperLogin) { userSettings.BusinessLegalName = null; userSettings.UserDisplayName = userId + " Associate"; // add generated guids userSettings.SiteMinderBusinessGuid = null; userSettings.SiteMinderGuid = GuidUtility.CreateIdForDynamics("bcsc", userSettings.UserDisplayName).ToString(); } if (userSettings.IsNewUserRegistration) { if (isDeveloperLogin) { // add generated guids userSettings.AccountId = userSettings.SiteMinderBusinessGuid; userSettings.ContactId = userSettings.SiteMinderGuid; } else if (isBCSCDeveloperLogin) { // set to null for now userSettings.AccountId = null; userSettings.ContactId = null; } _logger.LogDebug("New user registration:" + userSettings.UserDisplayName); _logger.LogDebug("userSettings.SiteMinderBusinessGuid:" + userSettings.SiteMinderBusinessGuid); _logger.LogDebug("userSettings.SiteMinderGuid:" + userSettings.SiteMinderGuid); _logger.LogDebug("userSettings.AccountId:" + userSettings.AccountId); _logger.LogDebug("userSettings.ContactId:" + userSettings.ContactId); } // Set account ID from authenticated user else if (userSettings.AuthenticatedUser != null) { // populate the business GUID. if (string.IsNullOrEmpty(userSettings.AccountId)) { userSettings.AccountId = userSettings.AuthenticatedUser.AccountId.ToString(); } if (string.IsNullOrEmpty(userSettings.ContactId)) { userSettings.ContactId = userSettings.AuthenticatedUser.ContactId.ToString(); } _logger.LogDebug("Returning user:"******"userSettings.AccountId:" + userSettings.AccountId); _logger.LogDebug("userSettings.ContactId:" + userSettings.ContactId); } } // add the worker settings if it is a new user. if (userSettings.IsNewUserRegistration && userSettings.NewWorker == null) { userSettings.NewWorker = new ViewModels.Worker(); userSettings.NewWorker.CopyHeaderValues(context.Request.Headers); } // add the worker settings if it is a new user. if (userSettings.IsNewUserRegistration && userSettings.NewContact == null) { userSettings.NewContact = new ViewModels.Contact(); userSettings.NewContact.CopyHeaderValues(context.Request.Headers); } // ************************************************** // Update user settings // ************************************************** UserSettings.SaveUserSettings(userSettings, context); // done! principal = userPrincipal; return(AuthenticateResult.Success(new AuthenticationTicket(principal, null, Options.Scheme))); } catch (Exception exception) { _logger.LogError(exception.Message); Console.WriteLine(exception); throw; } }
protected override async Task <AuthenticateResult> HandleAuthenticateAsync() { try { this.Logger.LogInformation("{LogKey:l} apikey handle", LogKeys.Authentication); if (this.Request.Host.Host.SafeEquals("localhost") && this.Options.IgnoreLocal) { // ignore for localhost var identity = new ClaimsIdentity( this.Options.Claims.Safe().Select(c => new Claim(c.Key, c.Value)) .Insert(new Claim(ClaimTypes.AuthenticationMethod, AuthenticationKeys.ApiKeyScheme)) .Insert(new Claim(ClaimTypes.Name, ClaimsIdentity.DefaultIssuer)) .DistinctBy(c => c.Type), this.Scheme.Name); var ticket = new AuthenticationTicket(new ClaimsPrincipal(identity), this.Scheme.Name); this.Logger.LogInformation($"{{LogKey:l}} apikey authenticated (name={identity.Name})", LogKeys.Authentication); return(AuthenticateResult.Success(ticket)); } string value; if (this.Request.Query.TryGetValue("apikey", out var queryValue)) { // also allow the auth header to be sent in the querystring (for easy dashboard usage) value = queryValue.ToString(); } else { if (!this.Request.Headers.ContainsKey(AuthenticationKeys.AuthorizationHeaderName)) { return(AuthenticateResult.NoResult()); //Authorization header not in request } if (!AuthenticationHeaderValue.TryParse(this.Request.Headers[AuthenticationKeys.AuthorizationHeaderName], out var headerValue)) { return(AuthenticateResult.NoResult()); //Invalid Authorization header } else { value = headerValue.Parameter; } if (!AuthenticationKeys.ApiKeyScheme.Equals(headerValue.Scheme, StringComparison.OrdinalIgnoreCase)) { return(AuthenticateResult.NoResult()); //Not a apikey authentication header } } if (value.IsNullOrEmpty()) { return(AuthenticateResult.NoResult()); //No apikey authentication value in header or query } //var context = new ApiKeyValidationContext(this.Context, this.Scheme, this.Options) { ApiKey = headerValue.Parameter }; //await this.Events.OnValidation(context); //if (context.Result != null) //{ // return context.Result; //} #pragma warning disable SA1008 // Opening parenthesis must be spaced correctly var(authenticated, claims) = this.service.Validate(value); #pragma warning restore SA1008 // Opening parenthesis must be spaced correctly if (authenticated) { var identity = new ClaimsIdentity( this.Options.Claims.Safe().Select(c => new Claim(c.Key, c.Value)).Concat(claims.Safe()) .Insert(new Claim(ClaimTypes.AuthenticationMethod, AuthenticationKeys.ApiKeyScheme)).DistinctBy(c => c.Type), this.Scheme.Name); var ticket = new AuthenticationTicket(new ClaimsPrincipal(identity), this.Scheme.Name); this.Logger.LogInformation($"{{LogKey:l}} apikey authenticated (name={identity.Name})", LogKeys.Authentication); return(AuthenticateResult.Success(ticket)); } this.Logger.LogWarning("{LogKey:l} apikey not authenticated", LogKeys.Authentication); return(AuthenticateResult.Fail("not authenticated")); } catch (Exception ex) { this.Logger.LogError(ex, $"{{LogKey:l}} {ex.Message}", LogKeys.Authentication); var context = new ErrorContext(this.Context, this.Scheme, this.Options) { Exception = ex }; if (this.Events != null) { await this.Events.Error(context); if (context.Result != null) { return(context.Result); } } throw; } }
protected override async Task <AuthenticateResult> HandleAuthenticateAsync() { string token = Options.TokenRetriever(Context.Request); if (token.IsMissing()) { return(AuthenticateResult.Skip()); } if (token.Contains('.') && Options.SkipTokensWithDots) { _logger.LogTrace("Token contains a dot - skipped because SkipTokensWithDots is set."); return(AuthenticateResult.Skip()); } // Resolve request generator _requestGenerator = Context.RequestServices.GetService <IIntrospectionRequestGenerator>() ?? new DefaultIntrospectionRequestGenerator(); if (Options.EnableCaching) { var claims = await _cache.GetClaimsAsync(token).ConfigureAwait(false); if (claims != null && await _requestGenerator.UseCacheAsync(Context.Request, claims)) { var ticket = CreateTicket(claims); _logger.LogTrace("Token found in cache."); if (Options.SaveToken) { ticket.Properties.StoreTokens(new[] { new AuthenticationToken { Name = "access_token", Value = token } }); } return(AuthenticateResult.Success(ticket)); } _logger.LogTrace("Token is not cached, or the introspection response generator rejected the currently cached claims."); } // Use a LazyAsync to ensure only one thread is requesting introspection for a token - the rest will wait for the result var lazyIntrospection = _lazyTokenIntrospections.GetOrAdd(token, CreateLazyIntrospection); try { var response = await lazyIntrospection.Value.ConfigureAwait(false); if (response.IsError) { _logger.LogError("Error returned from introspection endpoint: " + response.Error); return(AuthenticateResult.Fail("Error returned from introspection endpoint: " + response.Error)); } if (response.IsActive) { var ticket = CreateTicket(response.Claims); if (Options.SaveToken) { ticket.Properties.StoreTokens(new[] { new AuthenticationToken { Name = "access_token", Value = token } }); } if (Options.EnableCaching) { await _cache.SetClaimsAsync(token, response.Claims, Options.CacheDuration, _logger).ConfigureAwait(false); } return(AuthenticateResult.Success(ticket)); } else { return(AuthenticateResult.Fail("Token is not active.")); } } finally { // If caching is on and it succeeded, the claims are now in the cache. // If caching is off and it succeeded, the claims will be discarded. // Either way, we want to remove the temporary store of claims for this token because it is only intended for de-duping fetch requests AsyncLazy <IntrospectionResponse> removed; _lazyTokenIntrospections.TryRemove(token, out removed); } }
public async Task GetLabOrders() { // Setup string hdid = "EXTRIOYFPNX35TWEBUAJ3DNFDFXSYTBC6J4M76GYE3HC5ER2NKWQ"; string token = "Fake Access Token"; string userId = "1001"; IHeaderDictionary headerDictionary = new HeaderDictionary(); headerDictionary.Add("Authorization", token); Mock <HttpRequest> httpRequestMock = new Mock <HttpRequest>(); httpRequestMock.Setup(s => s.Headers).Returns(headerDictionary); List <Claim> claims = new List <Claim>() { new Claim(ClaimTypes.Name, "username"), new Claim(ClaimTypes.NameIdentifier, userId), new Claim("hdid", hdid), }; ClaimsIdentity identity = new ClaimsIdentity(claims, "TestAuth"); ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(identity); Mock <HttpContext> httpContextMock = new Mock <HttpContext>(); httpContextMock.Setup(s => s.User).Returns(claimsPrincipal); httpContextMock.Setup(s => s.Request).Returns(httpRequestMock.Object); Mock <IHttpContextAccessor> httpContextAccessorMock = new Mock <IHttpContextAccessor>(); httpContextAccessorMock.Setup(s => s.HttpContext).Returns(httpContextMock.Object); Mock <IAuthenticationService> authenticationMock = new Mock <IAuthenticationService>(); httpContextAccessorMock .Setup(x => x.HttpContext !.RequestServices.GetService(typeof(IAuthenticationService))) .Returns(authenticationMock.Object); var authResult = AuthenticateResult.Success(new AuthenticationTicket(claimsPrincipal, JwtBearerDefaults.AuthenticationScheme)); authResult.Properties !.StoreTokens(new[] { new AuthenticationToken { Name = "access_token", Value = token, }, }); authenticationMock .Setup(x => x.AuthenticateAsync(httpContextAccessorMock.Object !.HttpContext !, It.IsAny <string>())) .ReturnsAsync(authResult); Mock <ILaboratoryService> svcMock = new Mock <ILaboratoryService>(); svcMock.Setup(s => s.GetLaboratoryOrders(token, hdid, 0)).ReturnsAsync(new RequestResult <IEnumerable <LaboratoryModel> >() { ResultStatus = Common.Constants.ResultType.Success, TotalResultCount = 0, ResourcePayload = new List <LaboratoryModel>(), }); using var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole()); LaboratoryController controller = new LaboratoryController(loggerFactory.CreateLogger <LaboratoryController>(), svcMock.Object, httpContextAccessorMock.Object); // Act IActionResult actual = await controller.GetLaboratoryOrders(hdid).ConfigureAwait(true); // Verify Assert.IsType <JsonResult>(actual); JsonResult jsonResult = (JsonResult)actual; Assert.IsType <RequestResult <IEnumerable <LaboratoryModel> > >(jsonResult.Value); RequestResult <IEnumerable <LaboratoryModel> > result = (RequestResult <IEnumerable <LaboratoryModel> >)jsonResult.Value; Assert.True(result.ResultStatus == Common.Constants.ResultType.Success); }
#pragma warning disable 1998 protected override async Task <AuthenticateResult> HandleAuthenticateAsync() { return(AuthenticateResult.Success(ticket: null)); }
//public async Task<HttpContext> Authenticate(ClientContext clientContext, string authorization, string scheme) { // var authenticationService = _serviceProvider.GetRequiredService<IAuthenticationService>(); // var ctx = new DefaultHttpContext(); // ctx.RequestServices = _serviceProvider; // if (String.IsNullOrWhiteSpace(scheme)) { // var defaultScheme = await _schemes.GetDefaultAuthenticateSchemeAsync(); // scheme = defaultScheme?.Name; // } // AuthenticateResult authenticateResult; // if (clientContext.UserValidUntil < DateTime.Now) { // if (!authorization.Contains(" ")) { // authorization = $"Bearer {authorization}"; // } // ctx.Request.Headers["Authorization"] = authorization; // authenticateResult = await authenticationService.AuthenticateAsync(ctx, scheme); // } else { // var t = new AuthenticationTicket(clientContext.User, clientContext.User.Identity.AuthenticationType); // authenticateResult = AuthenticateResult.Success(t); // } // ctx.User = authenticateResult.Principal; // clientContext.SetPrincipal(ctx.User); // return ctx; //} public async Task <PolicyAuthorizationResult> Authorize(ClientContext clientContext, string authorization, MethodInfo methodInfo) { var authorizeData = methodInfo.GetAuthorizeData(); if (!authorizeData.Any()) { return(PolicyAuthorizationResult.Success()); } var authenticationService = _serviceProvider.GetRequiredService <IAuthenticationService>(); var policyEvaluator = _serviceProvider.GetRequiredService <IPolicyEvaluator>(); var policyProvider = _serviceProvider.GetRequiredService <IAuthorizationPolicyProvider>(); if (!authorizeData.Any()) { authorizeData = methodInfo.DeclaringType?.GetCustomAttributes <AuthorizeAttribute>().ToList() ?? new List <AuthorizeAttribute>(); } var policy = await AuthorizationPolicy.CombineAsync(policyProvider, authorizeData); if (policy == null) { return(PolicyAuthorizationResult.Success()); } var ctx = new DefaultHttpContext(); ctx.RequestServices = _serviceProvider; AuthenticateResult authenticateResult = AuthenticateResult.NoResult(); Console.WriteLine($"{clientContext.UserValidUntil} - {DateTime.Now}"); if (clientContext.UserValidUntil < DateTime.Now) { if (!authorization.Contains(" ")) { authorization = $"Bearer {authorization}"; } ctx.Request.Headers["Authorization"] = authorization; foreach (var policyAuthenticationScheme in policy.AuthenticationSchemes) { authenticateResult = await authenticationService.AuthenticateAsync(ctx, policyAuthenticationScheme); if (authenticateResult.Succeeded) { clientContext.SetPrincipal(authenticateResult.Principal); break; } } } else { var t = new AuthenticationTicket(clientContext.User, clientContext.User.Identity.AuthenticationType); authenticateResult = AuthenticateResult.Success(t); } ctx.User = authenticateResult.Principal; if (methodInfo.GetCustomAttribute <AllowAnonymousAttribute>() != null) { return(PolicyAuthorizationResult.Success()); } var authorizeResult = await policyEvaluator.AuthorizeAsync(policy, authenticateResult, ctx, clientContext); return(authorizeResult); }
protected override Task <AuthenticateResult> HandleAuthenticateAsync() { var principal = new ClaimsPrincipal(); return(Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(principal, new AuthenticationProperties(), Scheme.Name)))); }
protected override async Task <AuthenticateResult> HandleAuthenticateAsync() { var notification = new MatchEndpointContext(Context, Options); if (Options.AuthorizationEndpointPath.HasValue && Options.AuthorizationEndpointPath == Request.Path) { notification.MatchesAuthorizationEndpoint(); } else if (Options.LogoutEndpointPath.HasValue && Options.LogoutEndpointPath == Request.Path) { notification.MatchesLogoutEndpoint(); } else if (Options.ProfileEndpointPath.HasValue && Options.ProfileEndpointPath == Request.Path) { notification.MatchesProfileEndpoint(); } await Options.Provider.MatchEndpoint(notification); if (!notification.IsAuthorizationEndpoint && !notification.IsLogoutEndpoint && !notification.IsProfileEndpoint) { return(null); } // Try to retrieve the current OpenID Connect request from the ASP.NET context. // If the request cannot be found, this means that this middleware was configured // to use the automatic authentication mode and that HandleAuthenticateAsync // was invoked before Invoke*EndpointAsync: in this case, the OpenID Connect // request is directly extracted from the query string or the request form. var request = Context.GetOpenIdConnectRequest(); if (request == null) { if (string.Equals(Request.Method, "GET", StringComparison.OrdinalIgnoreCase)) { request = new OpenIdConnectMessage(Request.Query.ToDictionary()); } else if (string.Equals(Request.Method, "POST", StringComparison.OrdinalIgnoreCase)) { if (string.IsNullOrEmpty(Request.ContentType)) { return(null); } else if (!Request.ContentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase)) { return(null); } var form = await Request.ReadFormAsync(Context.RequestAborted); request = new OpenIdConnectMessage(form.ToDictionary()); } } // Missing or invalid requests are ignored in HandleAuthenticateAsync: // in this case, null is always returned to indicate authentication failed. if (request == null) { return(null); } if (notification.IsAuthorizationEndpoint || notification.IsLogoutEndpoint) { if (string.IsNullOrEmpty(request.IdTokenHint)) { return(null); } var ticket = await ReceiveIdentityTokenAsync(request.IdTokenHint, request); if (ticket == null) { Logger.LogVerbose("Invalid id_token_hint"); return(null); } // Tickets are returned even if they // are considered invalid (e.g expired). return(AuthenticateResult.Success(ticket)); } else if (notification.IsProfileEndpoint) { string token; if (!string.IsNullOrEmpty(request.AccessToken)) { token = request.AccessToken; } else { string header = Request.Headers[HeaderNames.Authorization]; if (string.IsNullOrEmpty(header)) { return(null); } if (!header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) { return(null); } token = header.Substring("Bearer ".Length); if (string.IsNullOrWhiteSpace(token)) { return(null); } } var ticket = await ReceiveAccessTokenAsync(token, request); if (ticket == null) { Logger.LogVerbose("Invalid access_token"); return(null); } if (!ticket.Properties.ExpiresUtc.HasValue || ticket.Properties.ExpiresUtc < Options.SystemClock.UtcNow) { Logger.LogVerbose("Expired access_token"); return(null); } return(AuthenticateResult.Success(ticket)); } return(null); }
private static TestServer CreateServer(Action <IServiceCollection> configureServices = null, Func <HttpContext, Task> testpath = null, Uri baseAddress = null, bool testCore = false) { var builder = new WebHostBuilder() .Configure(app => { app.UseAuthentication(); app.Use(async(context, next) => { var req = context.Request; var res = context.Response; var userManager = context.RequestServices.GetRequiredService <UserManager <PocoUser> >(); var roleManager = context.RequestServices.GetRequiredService <RoleManager <PocoRole> >(); var signInManager = context.RequestServices.GetRequiredService <SignInManager <PocoUser> >(); PathString remainder; if (req.Path == new PathString("/normal")) { res.StatusCode = 200; } else if (req.Path == new PathString("/createMe")) { var user = new PocoUser("hao"); var result = await userManager.CreateAsync(user, TestPassword); if (result.Succeeded) { result = await roleManager.CreateAsync(new PocoRole("role")); } if (result.Succeeded) { result = await userManager.AddToRoleAsync(user, "role"); } res.StatusCode = result.Succeeded ? 200 : 500; } else if (req.Path == new PathString("/createSimple")) { var result = await userManager.CreateAsync(new PocoUser("simple"), "aaaaaa"); res.StatusCode = result.Succeeded ? 200 : 500; } else if (req.Path == new PathString("/signoutEverywhere")) { var user = await userManager.FindByNameAsync("hao"); var result = await userManager.UpdateSecurityStampAsync(user); res.StatusCode = result.Succeeded ? 200 : 500; } else if (req.Path.StartsWithSegments(new PathString("/pwdLogin"), out remainder)) { var isPersistent = bool.Parse(remainder.Value.Substring(1)); var result = await signInManager.PasswordSignInAsync("hao", TestPassword, isPersistent, false); res.StatusCode = result.Succeeded ? 200 : 500; } else if (req.Path == new PathString("/twofactorRememeber")) { var user = await userManager.FindByNameAsync("hao"); await signInManager.RememberTwoFactorClientAsync(user); res.StatusCode = 200; } else if (req.Path == new PathString("/isTwoFactorRememebered")) { var user = await userManager.FindByNameAsync("hao"); var result = await signInManager.IsTwoFactorClientRememberedAsync(user); res.StatusCode = result ? 200 : 500; } else if (req.Path == new PathString("/hasTwoFactorUserId")) { var result = await context.AuthenticateAsync(IdentityConstants.TwoFactorUserIdScheme); res.StatusCode = result.Succeeded ? 200 : 500; } else if (req.Path == new PathString("/me")) { await DescribeAsync(res, AuthenticateResult.Success(new AuthenticationTicket(context.User, null, "Application"))); } else if (req.Path.StartsWithSegments(new PathString("/me"), out remainder)) { var auth = await context.AuthenticateAsync(remainder.Value.Substring(1)); await DescribeAsync(res, auth); } else if (req.Path == new PathString("/testpath") && testpath != null) { await testpath(context); } else { await next(); } }); }) .ConfigureServices(services => { if (testCore) { services.AddIdentityCore <PocoUser>() .AddRoles <PocoRole>() .AddSignInManager() .AddDefaultTokenProviders(); services.AddAuthentication(IdentityConstants.ApplicationScheme).AddIdentityCookies(); } else { services.AddIdentity <PocoUser, PocoRole>().AddDefaultTokenProviders(); } var store = new InMemoryStore <PocoUser, PocoRole>(); services.AddSingleton <IUserStore <PocoUser> >(store); services.AddSingleton <IRoleStore <PocoRole> >(store); configureServices?.Invoke(services); }); var server = new TestServer(builder); server.BaseAddress = baseAddress; return(server); }
public IServiceProvider ConfigureServices(IServiceCollection services) { services .AddDbContext <CheckContext>(options => { var path = Path.Combine(HostingEnvironment.ContentRootPath, "CheckRepublic.sqlite3"); options.UseSqlite($"Filename={path}"); }); services.AddTransient <ICheckBatchRunner, CheckBatchRunner>(); services.AddTransient <ICheckBatchService, CheckBatchService>(); services.AddTransient <ICheckFactory, ServiceProviderCheckFactory>(); services.AddTransient <ICheckNotificationService, CheckNotificationService>(); services.AddTransient <ICheckPersister, CheckPersister>(); services.AddTransient <ICheckResultService, CheckResultService>(); services.AddTransient <ICheckRunner, CheckRunner>(); services.AddTransient <ICheckRunnerService, CheckRunnerService>(); services.AddTransient <ICheckService, CheckService>(); services.AddTransient <IEntityMapper, EntityMapper>(); services.AddTransient <IHealthService, HealthService>(); services.AddTransient <IHeartbeatService, HeartbeatService>(); services.AddTransient <IHeartGroupService, HeartGroupService>(); services.AddTransient <IMigrationService, MigrationService>(); services.AddTransient <INotificationRunnerService, NotificationRunnerService>(); services.AddTransient <IRunnerMapper, RunnerMapper>(); services.AddTransient <ISystemClock, SystemClock>(); services.AddTransient <IHeartbeatCheck, HeartbeatCheck>(); services.AddTransient <IHttpJTokenCheck, HttpJTokenCheck>(); services.AddTransient <IHttpResponseStreamCheck, HttpResponseStreamCheck>(); services.AddTransient <IHttpSubstringCheck, HttpSubstringCheck>(); services.AddTransient <ICheck, BlogUpCheck>(); services.AddTransient <ICheck, ConnectorRideLatestJsonCheck>(); services.AddTransient <ICheck, ConnectorRideScrapeStatusCheck>(); services.AddTransient <ICheck, NuGetToolsUpCheck>(); services.AddTransient <ICheck, WintalloUpCheck>(); services.AddTransient <ICheck, ExplorePackagesUpCheck>(); services.AddOptions(); services.Configure <WebsiteOptions>(Configuration); services.Configure <GroupMeOptions>(Configuration.GetSection("GroupMe")); if (string.IsNullOrEmpty(Configuration.GetValue <string>("GroupMe:AccessToken")) || string.IsNullOrEmpty(Configuration.GetValue <string>("GroupMe:BotId"))) { services.AddTransient <INotificationSender, LoggerNotificationSender>(); } else { services.AddTransient <INotificationSender, GroupMeNotificationSender>(); } services.AddSingleton <IAuthorizationHandler, AnonymousHandler>(); services .AddAuthorization(options => { var hasRead = !string.IsNullOrEmpty(Configuration.GetValue <string>("ReadPassword")); var hasWrite = !string.IsNullOrEmpty(Configuration.GetValue <string>("WritePassword")); var readRequirements = new List <string>(); var writeRequirements = new List <string>(); if (hasRead) { readRequirements.Add(AuthorizationConstants.ReaderRole); } if (hasWrite) { readRequirements.Add(AuthorizationConstants.WriterRole); writeRequirements.Add(AuthorizationConstants.WriterRole); } if (hasRead) { options.AddPolicy( AuthorizationConstants.ReadPolicy, policy => policy .RequireAuthenticatedUser() .AddRequirements(new RolesAuthorizationRequirement(readRequirements))); } else { options.AddPolicy( AuthorizationConstants.ReadPolicy, policy => policy .AddRequirements(new AnonymousRequirement())); } if (hasWrite) { options.AddPolicy( AuthorizationConstants.WritePolicy, policy => policy .RequireAuthenticatedUser() .AddRequirements(new RolesAuthorizationRequirement(writeRequirements))); } else { options.AddPolicy( AuthorizationConstants.WritePolicy, policy => policy .AddRequirements(new AnonymousRequirement())); } }); services .AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme) .AddBasicAuthentication(options => { options.Realm = HostingEnvironment.ApplicationName; options.Events = new BasicAuthenticationEvents { OnValidatePrincipal = context => { var websiteOptions = ServiceProvider.GetService <IOptions <WebsiteOptions> >(); var claims = new List <Claim>(); var readPassword = websiteOptions.Value.ReadPassword; if (string.IsNullOrWhiteSpace(readPassword) || context.Password == readPassword) { claims.Add(new Claim(ClaimTypes.Role, AuthorizationConstants.ReaderRole)); } var writePassword = websiteOptions.Value.WritePassword; if (string.IsNullOrWhiteSpace(writePassword) || context.Password == writePassword) { claims.Add(new Claim(ClaimTypes.Role, AuthorizationConstants.WriterRole)); } var ticket = new AuthenticationTicket( new ClaimsPrincipal(new ClaimsIdentity(claims, BasicAuthenticationDefaults.AuthenticationScheme)), new AuthenticationProperties(), BasicAuthenticationDefaults.AuthenticationScheme); return(Task.FromResult(AuthenticateResult.Success(ticket))); } }; }); services .AddMvc(options => { }) .AddJsonOptions(options => { options.SerializerSettings.Converters.Add(new StringEnumConverter()); options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; }); ServiceProvider = services.BuildServiceProvider(); return(ServiceProvider); }
protected override async Task <AuthenticateResult> HandleRemoteAuthenticateAsync() { var state = Request.Query["state"]; var properties = Options.StateDataFormat.Unprotect(state); if (properties == null) { return(AuthenticateResult.Fail("The oauth state was missing or invalid.")); } if (!ValidateCorrelationId(properties)) { return(AuthenticateResult.Fail("Correlation failed.")); } ClaimsIdentity identity; if (Context.User.Identity.IsAuthenticated && Context.User.Identity.AuthenticationType == Options.AuthenticationScheme) { identity = (ClaimsIdentity)Context.User.Identity; } else { identity = new ClaimsIdentity(Options.AuthenticationScheme); } Uri spHostUrl; if (!Uri.TryCreate(Request.Query[SPAddinAuthenticationDefaults.HostUrlKey], UriKind.Absolute, out spHostUrl)) { throw new Exception("Can not get host url from query string"); } Uri spAppWebUrl; if (Uri.TryCreate(Request.Query[SPAddinAuthenticationDefaults.AppWebUrlKey], UriKind.Absolute, out spAppWebUrl)) { identity.AddClaim(new Claim(SPAddinClaimTypes.SPAppWebUrl, spAppWebUrl.AbsoluteUri)); } string accessToken; if (TokenHelper.IsHighTrustApp()) { //TODO throw new NotImplementedException("S2S authenticaiton is not implemented yet"); } else { var contextTokenString = TokenHelper.GetContextTokenFromRequest(Request); var contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, new Uri(CurrentUri).Authority); identity.AddClaim(new Claim(SPAddinClaimTypes.RefreshToken, contextToken.RefreshToken)); identity.AddClaim(new Claim(SPAddinClaimTypes.Realm, contextToken.Realm)); identity.AddClaim(new Claim(SPAddinClaimTypes.TargetPrincipalName, contextToken.TargetPrincipalName)); identity.AddClaim(new Claim(SPAddinClaimTypes.CacheKey, contextToken.CacheKey)); accessToken = TokenHelper.GetAcsAccessToken(contextToken.RefreshToken, contextToken.TargetPrincipalName, spHostUrl.Authority, contextToken.Realm); } var ticket = CreateTicket(identity, properties, accessToken, spHostUrl); if (ticket != null) { ((ClaimsIdentity)ticket.Principal.Identity).AddClaim(new Claim(SPAddinClaimTypes.SPAddinAuthentication, "1")); return(AuthenticateResult.Success(ticket)); } return(AuthenticateResult.Fail("Failed to retrieve user information from remote server.")); }
protected internal virtual AuthenticateResult CreateAuthenticateResult(ClaimsPrincipal principal) { return(AuthenticateResult.Success(new AuthenticationTicket(principal, "Ticket-authentication-scheme"))); }