async Task IAuthenticationFilter.AuthenticateAsync( HttpAuthenticationContext context, CancellationToken cancellationToken ) { HttpRequestMessage request = context.Request; ID2LPrincipal principal; try { principal = await AuthenticateAsync( context ).SafeAsync(); } catch( ValidationException e ) { m_log.Warn( "Authentication failed", e ); context.ErrorResult = new AuthenticationFailureResult( e ); return; } catch( Exception e ) { m_log.Error( "Unexpected exception during authentication", e ); throw; } // Note: the principal at this point may be anonymous if no credentials // were sent. This can be guarded against with the authorization attributes // and is by DefaultAuthorizationAttribute. // Add to request context so things that can't use DI (e.g. extension // methods) can get the principal. context.Principal = new D2LPrincipalToIPrincipalAdaptor( principal ); // We're using a callback here to avoid coupling to Unity (for example) m_principalDependencyRegistry.Register( context, principal ); }
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { HttpRequestMessage request = context.Request; AuthenticationHeaderValue authorization = request.Headers.Authorization; if (authorization == null || authorization.Scheme != AuthorizationScheme) { context.Principal = _anonymousPrincipal; return; } string user; string password; if (!ExtractUserNameAndPassword(authorization.Parameter, out user, out password)) { context.ErrorResult = new AuthenticationFailureResult("Invalid credentials", request); return; } context.Principal = await Authenticate(user, password); if (context.Principal == null) context.ErrorResult = new AuthenticationFailureResult("Invalid username or password", request); }
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { var req = context.Request; if (req.Headers.Authorization != null && req.Headers.Authorization.Scheme.Equals("basic", StringComparison.OrdinalIgnoreCase)) { var encoding = Encoding.GetEncoding("iso-8859-1"); var credentials = encoding.GetString(Convert.FromBase64String(req.Headers.Authorization.Parameter)); var parts = credentials.Split(':'); var user = parts[0].Trim(); var password = parts[1].Trim(); //TODO: User/ password if (user.Equals(GetUserName()) && password.Equals(GetPassword())) { var claims = new List<Claim>() { new Claim(ClaimTypes.Name, "Miguel Angel Martín Hrdez") }; var identity = new ClaimsIdentity(claims, "Basic"); var principal = new ClaimsPrincipal(new[] { identity }); context.Principal = principal; } else { context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request); } } else { context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request); } return Task.FromResult(0); }
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { if (CurrentFilter == null) return Task.FromResult(0); context.Principal = Principal; return CurrentFilter.AuthenticateAsync(context, cancellationToken); }
private async Task<ID2LPrincipal> AuthenticateAsync( HttpAuthenticationContext context ) { ID2LPrincipal principal = await m_requestAuthenticator .AuthenticateAsync( context.Request ) .SafeAsync(); return principal; }
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously { HttpRequestMessage request = context.Request; var workContext = context.ActionContext.ControllerContext.GetWorkContext(); var authenticator = workContext.Resolve<IBasicAuthenticationService>(); var credentials = authenticator.GetCredentials(request.Headers.Authorization); if ( credentials == null ) { this.Logger.Warning( "Basic authentication failed: missing credentials {0} for {1}", request.Method, request.RequestUri); context.ErrorResult = new AuthenticationFailureResult("Missing credentials", request); return; } var user = authenticator.GetUserForCredentials(credentials); if ( user == null ) { this.Logger.Warning( "Basic authentication failed: invalid credentials {0} {1} for {2}", credentials.Username, request.Method, request.RequestUri); context.ErrorResult = new AuthenticationFailureResult("Invalid username or password", request); } else { authenticator.SetAuthenticatedUserForRequest(user); } }
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { var tokenString = context?.Request?.Headers?.Authorization?.Parameter; if (string.IsNullOrEmpty(tokenString)) { SetupUnauthenticated(); return; } var tokenInfo = _authorizer.GetTokenInfo(tokenString); if (tokenInfo == null) { context.ErrorResult = new UnauthorizedResult( new AuthenticationHeaderValue[] {}, context.Request); await context.ErrorResult.ExecuteAsync(cancellationToken); SetupUnauthenticated(); return; } var identity = new LodIdentity(tokenInfo.UserId, true); var principal = new LodPrincipal(tokenInfo.Role, identity); Thread.CurrentPrincipal = principal; context.Principal = principal; }
public void Authenticate(HttpAuthenticationContext context) { if (context == null) return; if (context.Principal != null && context.Principal.Identity.IsAuthenticated) return; var queryString = HttpUtility.ParseQueryString(context.Request.RequestUri.Query.ToString()); if (queryString != null) { var apiKeyValues = queryString.GetValues("ApiKey"); if (apiKeyValues != null) { var apiKey = apiKeyValues.GetValue(0); IPrincipal principal = null; if (Auth.Validate(apiKey, out principal)) { context.Principal = principal; Thread.CurrentPrincipal = principal; } } } }
/// <inheritdoc /> public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { if (context == null) { throw new ArgumentNullException("context"); } HttpRequestMessage request = context.Request; if (request == null) { throw new InvalidOperationException(OwinResources.HttpAuthenticationContext_RequestMustNotBeNull); } IAuthenticationManager authenticationManager = GetAuthenticationManagerOrThrow(request); cancellationToken.ThrowIfCancellationRequested(); AuthenticateResult result = await authenticationManager.AuthenticateAsync(_authenticationType); if (result != null) { IIdentity identity = result.Identity; if (identity != null) { context.Principal = new ClaimsPrincipal(identity); } } }
public System.Threading.Tasks.Task AuthenticateAsync(HttpAuthenticationContext context, System.Threading.CancellationToken cancellationToken) { var request = context.Request; var authorization = request.Headers.Authorization; var validation = Task.FromResult(Validate(request, authorization, context)); var authentication = validation.ContinueWith( tupleTask => { if (tupleTask.Result != null) { var tuple = tupleTask.Result; var username = tuple.Item2.Item1; var password = tuple.Item2.Item2; var principal = Authenticate(username, password, cancellationToken); if (principal == null) { context.ErrorResult = new AuthenticationFailureResult("Invalid username or password", request); } else { context.Principal = principal; } } else { context.ErrorResult = new AuthenticationFailureResult("Authorization required", request); } } ); return authentication; }
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { IPrincipal user = null; AuthenticationHeaderValue headerValue = context.Request.Headers.Authorization; if (null != headerValue && headerValue.Scheme == "Basic") { string credential = Encoding.Default.GetString(Convert.FromBase64String(headerValue.Parameter)); string[] split = credential.Split(':'); if (split.Length == 2) { string userName = split[0]; string password; if (userAccounters.TryGetValue(userName, out password)) { if (password == split[1]) { GenericIdentity identity = new GenericIdentity(userName); user = new GenericPrincipal(identity, new string[0]); } } } } context.Principal = user; return Task.FromResult<object>(null); }
public System.Threading.Tasks.Task AuthenticateAsync(System.Web.Http.Filters.HttpAuthenticationContext context, System.Threading.CancellationToken cancellationToken) { IPrincipal user = null; AuthenticationHeaderValue headerValue = context.Request.Headers.Authorization; if (headerValue != null && headerValue.Scheme == "Basic") { string credential = Encoding.Default.GetString(Convert.FromBase64String(headerValue.Parameter)); string[] split = credential.Split(':'); if (split.Length == 2) { string userName = split[0]; string password; if (_userAccounts.TryGetValue(userName, out password)) { if (password == split[1]) { GenericIdentity identity = new GenericIdentity(userName, "Basic"); user = new GenericPrincipal(identity, new string[0]); } } } } context.Principal = user; return(Task.FromResult <object>(null)); }
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { var credentials = ParseAuthentication(context.Request.Headers.Authorization); if (credentials != null) { var user = _config.Users.OfType<User>().FirstOrDefault(x => x.Username.Equals(credentials.UserName, StringComparison.InvariantCultureIgnoreCase)); if (user != null) { if (string.IsNullOrEmpty(user.HashAlgorithm)) { if (credentials.Password == user.Password) context.Principal = BuildPrincipal(user); } else { var algo = HashAlgorithm.Create(user.HashAlgorithm); if (algo == null) throw new ConfigurationErrorsException($"No known hash algorithm called {user.HashAlgorithm}."); string hashedPassword = BitConverter.ToString(algo.ComputeHash(Encoding.UTF8.GetBytes(credentials.Password))).Replace("-", ""); if (hashedPassword == user.Password.ToUpperInvariant()) context.Principal = BuildPrincipal(user); } } } return Task.FromResult(true); }
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { var request = context.Request; var authorization = request.Headers.Authorization; // No credentials where supplied if (authorization == null) return; // The server does not recognize the authorization scheme. if (authorization.Scheme != "Basic") return; // The credentials were bad. if (String.IsNullOrEmpty(authorization.Parameter)) { context.ErrorResult = new AuthenticationFailureResult("Missing credentials", request); return; } // Credentials were invalid var credentials = GetCredentialsFromRequest(authorization.Parameter); if(credentials == null) { context.ErrorResult = new AuthenticationFailureResult("Invalid credentials", request); return; } // Credentials were supplied and were either correct or not. var principal = await AuthenticateAsync(credentials, cancellationToken); if (principal == null) context.ErrorResult = new AuthenticationFailureResult("Invalid username or password", request); else context.Principal = principal; }
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { HttpRequestMessage request = context.Request; AuthenticationHeaderValue authorization = request.Headers.Authorization; if (authorization == null) return; if (authorization.Scheme != "Basic") return; if (String.IsNullOrEmpty(authorization.Parameter)) { context.ErrorResult = new AuthenticationFailureResult("Missing credentials", request); return; } Tuple<string, string> usernameAndPassword = ExtractUsernameAndPassword(authorization.Parameter); if(usernameAndPassword== null) { context.ErrorResult = new AuthenticationFailureResult("Invalid Credentials", request); return; } string username = usernameAndPassword.Item1; string password = usernameAndPassword.Item2; IPrincipal principal = await AuthenticateAsync(username, password, cancellationToken); if (principal == null) context.ErrorResult = new AuthenticationFailureResult("Invalid username or password", request); else context.Principal = principal; }
/// <inheritdoc /> public async Task<IAuthenticationResult> AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { if (context == null) { throw new ArgumentNullException("context"); } HttpRequestMessage request = context.Request; if (request == null) { throw new InvalidOperationException(OwinResources.HttpAuthenticationContext_RequestMustNotBeNull); } OwinRequest owinRequest = request.GetOwinRequest(); cancellationToken.ThrowIfCancellationRequested(); IIdentity identity = await owinRequest.AuthenticateAsync(_authenticationType); if (identity == null) { return null; } return new SucceededAuthenticationResult(new ClaimsPrincipal(identity)); }
public override void OnAuthentication(HttpAuthenticationContext context) { if (!Authenticate(context)) { context.ErrorResult = new StatusCodeResult(HttpStatusCode.Unauthorized, context.Request); } }
public void WrapperResolvesAuthenticationFilterFromDependencyScope() { var builder = new ContainerBuilder(); builder.Register<ILogger>(c => new Logger()).InstancePerDependency(); var activationCount = 0; builder.Register<IAutofacAuthenticationFilter>(c => new TestAuthenticationFilter(c.Resolve<ILogger>())) .AsWebApiAuthenticationFilterFor<TestController>(c => c.Get()) .InstancePerRequest() .OnActivated(e => activationCount++); var container = builder.Build(); var resolver = new AutofacWebApiDependencyResolver(container); var configuration = new HttpConfiguration { DependencyResolver = resolver }; var requestMessage = new HttpRequestMessage(); requestMessage.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, configuration); var contollerContext = new HttpControllerContext { Request = requestMessage }; var controllerDescriptor = new HttpControllerDescriptor { ControllerType = typeof(TestController) }; var methodInfo = typeof(TestController).GetMethod("Get"); var actionDescriptor = new ReflectedHttpActionDescriptor(controllerDescriptor, methodInfo); var actionContext = new HttpActionContext(contollerContext, actionDescriptor); var context = new HttpAuthenticationContext(actionContext, Thread.CurrentPrincipal); var metadata = new FilterMetadata { ControllerType = typeof(TestController), FilterScope = FilterScope.Action, MethodInfo = methodInfo }; var wrapper = new AuthenticationFilterWrapper(metadata); wrapper.OnAuthenticate(context); Assert.That(activationCount, Is.EqualTo(1)); }
private bool GetAuthParameter(HttpAuthenticationContext context, out string parameter) { var request = context.Request; var auth = request.Headers.Authorization; parameter = String.Empty; if (auth == null) { context.ErrorResult = new AuthFailedResult("Not authentificated request. Provide auth data.", request); return false; } if (auth.Scheme != _container.Scheme) { context.ErrorResult = new AuthFailedResult("Unknown scheme", request); return false; } if (string.IsNullOrEmpty(auth.Parameter)) { context.ErrorResult = new AuthFailedResult("Missing credentials", request); return false; } parameter = auth.Parameter; //TODO: Parse parameters if needed //TODO: Check token not to be outdated return true; }
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { string parameter; if (!GetAuthParameter(context, out parameter)) { return Task.FromResult(0); } var data = _container.Get(parameter); if (data == null) { context.ErrorResult = new AuthFailedResult("Unauthorized access", context.Request); return Task.FromResult(0); } var claims = new List<Claim>() { new Claim(ClaimTypes.Name, data.Item1.FirstName), new Claim("Permission", data.Item2.Permissions.ToString()) }; var id = new ClaimsIdentity(claims, "Token"); var principal = new ClaimsPrincipal(new[] { id }); context.Principal = principal; return Task.FromResult(0); }
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { var token = string.Empty; IEnumerable<String> values; if (context.Request.Headers.TryGetValues("X-zvsToken", out values)) token = values.FirstOrDefault(); var authorizedTokens = new List<string>(_webApi2Plugin.TokensSettings.Split(',')); if (token == null || !authorizedTokens.Any(o => o.Trim().Equals(token))) { context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request); return Task.FromResult(0); } var claims = new List<Claim> { new Claim(ClaimTypes.Name, "ZvsApi User"), new Claim(ClaimTypes.Role, "All Access") }; var id = new ClaimsIdentity(claims, "StaticToken"); var principal = new ClaimsPrincipal(new[] { id }); context.Principal = principal; return Task.FromResult(0); }
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { var request = context.Request; var authorization = request.Headers.Authorization; if (authorization == null || authorization.Scheme != "Basic") { return; } if (string.IsNullOrEmpty(authorization.Parameter)) { context.ErrorResult = new AuthenticationFailureResult("Missing credentials", request); return; } var credentials = ExtractCredentials(authorization.Parameter); if (credentials == null) { context.ErrorResult = new AuthenticationFailureResult("Invalid credentials", request); return; } var principal = await AuthenticateAsync(credentials, cancellationToken); if (principal == null) { context.ErrorResult = new AuthenticationFailureResult("Invalid username or password", request); } else { context.Principal = principal; } }
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { var request = context.Request; if (string.IsNullOrEmpty(context.Principal.Identity.Name)) context.ErrorResult = new AuthenticationFailureResult("Not Authenticated", request); return Task.FromResult(0); }
public async Task AuthenticateAsync ( HttpAuthenticationContext context, System.Threading.CancellationToken cancellationToken ) { //// set //context.Principal //use context.ActionContext.RequestContext.Principal to get what already in the pipeline Helper.Write("Authentication", context.ActionContext.RequestContext.Principal); }
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { string userName = context.Request.Headers.GetValues("X-Identity").Single(); string[] roles = context.Request.Headers.GetValues("X-Roles").Single() .Split(new[] { ",", " " }, StringSplitOptions.RemoveEmptyEntries); context.Principal = new GenericPrincipal(new GenericIdentity(userName), roles); return _done; }
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { HttpRequestMessage request = context.Request; var scopeToken = request.Headers.FirstOrDefault(k => k.Key == "x-api-scope"); var token = scopeToken.Value.First().Split(' '); //Token is not in the Bearer XXXX format if (token == null || token.Length != 2) { return; } AuthenticationHeaderValue authorization = new AuthenticationHeaderValue(token[0], token[1]); // 2. If there are no credentials, do nothing. if (authorization == null) { return; } // 3. If there are credentials but the filter does not recognize the // authentication scheme, do nothing. if (authorization.Scheme != "Scope") { context.ErrorResult = new AuthenticationFailureResult("Unrecognized credentials.", request); return; } // 4. If there are credentials that the filter understands, try to validate them. // 5. If the credentials are bad, set the error result. if (String.IsNullOrEmpty(authorization.Parameter)) { context.ErrorResult = new AuthenticationFailureResult("Missing credentials", request); return; } var claimsList = await ValidateToken(authorization.Parameter); if(claimsList == null) { context.ErrorResult = new AuthenticationFailureResult("Invalid username or password", request); } else { ClaimsIdentity ident = new ClaimsIdentity(claimsList); IPrincipal principal = new ClaimsPrincipal(ident); if (principal == null) { context.ErrorResult = new AuthenticationFailureResult("Invalid username or password", request); } else { context.Principal = principal; } } }
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { HttpRequestMessage request = context.Request; AuthenticationHeaderValue authorization = request.Headers.Authorization; if (authorization == null) { // No authentication was attempted (for this authentication method). // Do not set either Principal (which would indicate success) or ErrorResult (indicating an error). return; } if (authorization.Scheme != "Basic") { // No authentication was attempted (for this authentication method). // Do not set either Principal (which would indicate success) or ErrorResult (indicating an error). return; } if (String.IsNullOrEmpty(authorization.Parameter)) { // Authentication was attempted but failed. Set ErrorResult to indicate an error. context.ErrorResult = new AuthenticationFailureResult("Missing credentials", request); return; } Tuple<string, string> userNameAndPasword = ExtractUserNameAndPassword(authorization.Parameter); if (userNameAndPasword == null) { // Authentication was attempted but failed. Set ErrorResult to indicate an error. context.ErrorResult = new AuthenticationFailureResult("Invalid credentials", request); return; } string userName = userNameAndPasword.Item1; string password = userNameAndPasword.Item2; IPrincipal principal = await AuthenticateAsync(userName, password, cancellationToken); if (principal == null) { // Authentication was attempted but failed. Set ErrorResult to indicate an error. context.ErrorResult = new AuthenticationFailureResult("Invalid username or password", request); } else { // Authentication was attempted and succeeded. Set Principal to the authenticated user. context.Principal = principal; } }
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { var identity = context.Principal.Identity; if (identity.IsAuthenticated) { } return Task.CompletedTask; }
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { await Task.Run(() => { IPrincipal incomingPrincipal = context.ActionContext.RequestContext.Principal; Debug.WriteLine(String.Format("Incoming principal in custom auth filter AuthenticateAsync method is authenticated: {0}", incomingPrincipal.Identity.IsAuthenticated)); IPrincipal genericPrincipal = new GenericPrincipal(new GenericIdentity("Andras", "CustomIdentification"), new string[] { "Admin", "PowerUser" }); context.Principal = genericPrincipal; }); }
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { AuthenticationHeaderValue authorization = context.Request.Headers.Authorization; if (string.Equals(authorization.Scheme, "Bearer", StringComparison.OrdinalIgnoreCase) && authorization.Parameter == Settings.BearerToken) { context.Principal = new ClientRolePrincipal(new SocialIdentity("Bearer")); } return Task.FromResult(0); }
/// <summary> /// Authenticates the request. /// </summary> /// <param name="context">The context.</param> /// <param name="cancellationToken">The cancellation token.</param> public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { Guard.NotNull(context, nameof(context)); if (context.ActionContext.RequestContext.IsLocal == false) { throw new OnlyLocalException(); } return Task.CompletedTask; }