public IActionResult Authenticate([FromBody] LoginModel dto) { var token = _authenticationProvider.Authenticate(dto.Login, dto.Password); if (token == null || !token.IsValid()) { return(Unauthorized()); } return(Ok(token)); }
public JsonResult JsonLogin(LoginModel model, string returnUrl) { if (ModelState.IsValid) { if (authenticationProvider.Authenticate(model.UserName, model.Password, model.RememberMe)) { return(Json(new { success = true, redirect = returnUrl })); } ModelState.AddModelError("", "The user name or password provided is incorrect."); return(Json(new { errors = GetErrorsFromModelState() })); } return(Json(new { errors = GetErrorsFromModelState() })); }
private async Task <(string username, bool success)> AuthenticateWithProvider( IAuthenticationProvider provider, string username, string password, User?resolvedUser) { try { var authenticationResult = provider is IRequiresResolvedUser requiresResolvedUser ? await requiresResolvedUser.Authenticate(username, password, resolvedUser).ConfigureAwait(false) : await provider.Authenticate(username, password).ConfigureAwait(false); if (authenticationResult.Username != username) { _logger.LogDebug("Authentication provider provided updated username {1}", authenticationResult.Username); username = authenticationResult.Username; } return(username, true); } catch (AuthenticationException ex) { _logger.LogError(ex, "Error authenticating with provider {Provider}", provider.Name); return(username, false); } }
public override void ServerSide(List <Common.Connections.Connection> ServerConnections, Common.Connections.Connection ThisConnection) { IAuthenticationProvider AuthProvider = StaticFunctions.GetAuthenticationProvider(); //GET THE AUTHENTICATION RESULT FROM THE AUTHENTICATE FUNCTION AuthResult tmpResult = AuthProvider.Authenticate(UserName, Password); //DOUBLE CHECK TO MAKE SURE THAT THE USERID WE GOT BACK IS NOT ALREADY IN USE if ((from a in ServerConnections where a.UserID == tmpResult.UserID && a != ThisConnection select a).Count() != 0) { //THROW AN ERROR BECAUSE A USER CAN NOT BE LOGGED IN TWICE new Message_Error() { Message = "Username cannot be logged in twice!" }.Send(ThisConnection); tmpResult.Success = false; //CLOSE THE CONNECTION SO THE USER MAY LOGIN THE NEXT TIME //TODO: SHOULD PROVIDE THIS CONNECTION A METHOD OF SAYING NOT TO LOG THEM OFF OR ATLEAST LETTING THEM KNOW WHY THEY ARE BEING LOGGED OFF (from a in ServerConnections where a.UserID == tmpResult.UserID && a != ThisConnection select a).First().TcpConnection.Close(); } //STORE THE RESULT FROM THE AUTHENTICATION CALL if (tmpResult.Success) { ThisConnection.UserID = tmpResult.UserID; ThisConnection.Authenticated = true; this.Success = tmpResult.Success; this.UserID = tmpResult.UserID; this.DisplayName = tmpResult.DisplayName; } //SEND THE RESPONSE BACK TO THE CLIENT Send(ThisConnection); }
public async Task <IActionResult> CompleteAuthentication(int id) { AuthenticatedSession authenticatedSession = await authenticatedSessionRepository.Get(id); ProviderInstance providerInstance = await providerRepository.GetInstance(authenticatedSession.Provider.ID); if (providerInstance == null) { return(RedirectToAction("Index", "Home")); } IAuthenticationProvider <object> authenticationProvider = await providerMappingService.CreateProvider <IAuthenticationProvider <object> >(providerInstance); try { authenticationProvider.Initialize($"http://{Request.Host}/Authentication/CompleteAuthentication?id={id}", data => StoreSession(id, data)); bool result = await authenticationProvider.Authenticate(Request.Query.ToDictionary(k => k.Key, v => v.Value.ToString())); } catch (Exception ex) { logger.LogError(ex, $"Failed to complete authentication for '{authenticatedSession.Name}'."); } return(RedirectToAction("Index")); }
public string Issue(ICredentials credentials) { var handler = new JwtSecurityTokenHandler(); if (_authenticationProvider.Authenticate(credentials)) { // Here, you should create or look up an identity for the user which is being authenticated. // For now, just creating a simple generic identity. ClaimsIdentity identity = new ClaimsIdentity(new GenericIdentity(credentials.Username.ToString(), "TokenAuth"), new[] { new Claim("EntityID", "1", ClaimValueTypes.Integer), new Claim("Username", credentials.Username, ClaimValueTypes.String), new Claim("Scope", "Login Play", ClaimValueTypes.String), }); var securityToken = handler.CreateJwtSecurityToken( issuer: _tokenOptions.Issuer, audience: _tokenOptions.Audience, signingCredentials: _tokenOptions.SigningCredentials, subject: identity, expires: DateTime.Now.AddSeconds(90) ); return(handler.WriteToken(securityToken)); } return(null); }
private async Task <Tuple <string, bool> > AuthenticateWithProvider(IAuthenticationProvider provider, string username, string password, User resolvedUser) { try { var requiresResolvedUser = provider as IRequiresResolvedUser; ProviderAuthenticationResult authenticationResult = null; if (requiresResolvedUser != null) { authenticationResult = await requiresResolvedUser.Authenticate(username, password, resolvedUser).ConfigureAwait(false); } else { authenticationResult = await provider.Authenticate(username, password).ConfigureAwait(false); } if (authenticationResult.Username != username) { _logger.LogDebug("Authentication provider provided updated username {1}", authenticationResult.Username); username = authenticationResult.Username; } return(new Tuple <string, bool>(username, true)); } catch (Exception ex) { _logger.LogError(ex, "Error authenticating with provider {provider}", provider.Name); return(new Tuple <string, bool>(username, false)); } }
private async Task <bool> AuthenticateAsync() { return(await Task.Factory.StartNew(() => { _authenticationProvider.Authenticate(Login, Password); return _authenticationProvider.AuthenticatedUser != null; })); }
public ActionResult Authenticate(string frob) { var authenticationInfo = _authenticationProvider.Authenticate(frob); if (authenticationInfo.IsAuthenticated) { _logger.Info(string.Format(UserHasLoggedInMessage, authenticationInfo.UserAlias)); } return(RedirectToLastPage()); }
public void Execute() { var context = RequestContext.Current; var apiName = context.RequestModel.ApiName; var accessKey = context.RequestModel.AccessKey; if (!_provider.Authenticate(apiName, accessKey)) { throw new ApiGatewayException(401, "Not Allowed"); } }
/// <summary> /// Authenticates a user by calling the authentication provider's Authenticate API. /// </summary> /// <param name="userName">Name of the user.</param> /// <param name="password">The password.</param> /// <returns>The <see cref="AuthenticatedToken"/>.</returns> private AuthenticatedToken AuthenticateUser(string userName, string password) { #region Parameter Validation if (string.IsNullOrEmpty(userName)) { return(null); } #endregion UserNameSecurityToken token = new UserNameSecurityToken(userName, password); AuthenticatedToken userToken = provider.Authenticate(token); return(userToken); }
public bool SignIn(string username, string password, IAuthenticationProvider authProvider) { if (authProvider.Authenticate(username, password)) { this.Username = authProvider.Username; this.UserType = authProvider.UserType; this.UserId = authProvider.UserId; } this.IsAuthenticated = authProvider.IsAuthenticated; return this.IsAuthenticated; }
public static Task <IPrincipal> GetUser(IAuthenticationProvider authenticationProvider, Metadata requestHeaders) { var principalSource = new TaskCompletionSource <IPrincipal>(); if (AuthenticationHeaderValue.TryParse( requestHeaders.FirstOrDefault(x => x.Key == Constants.Headers.Authorization)?.Value, out var authenticationHeader) && authenticationHeader.Scheme == Constants.Headers.BasicScheme && TryDecodeCredential(authenticationHeader.Parameter, out var username, out var password)) { authenticationProvider.Authenticate( new GrpcBasicAuthenticationRequest(principalSource, username, password)); }
public bool Authenticate(HttpContext context, out HttpAuthenticationRequest request) { if (!context.Request.Headers.TryGetValue("authorization", out var values) || values.Count != 1 || !AuthenticationHeaderValue.TryParse( values[0], out var authenticationHeader) || authenticationHeader.Scheme != "Bearer") { request = null; return(false); } request = new HttpAuthenticationRequest(context, authenticationHeader.Parameter); _internalAuthenticationProvider.Authenticate(request); return(true); }
public void CheckIfAuthenticationSucceedsWithValidCredentialsThroughInterface() { IAuthenticationProvider IAuthProvider = AuthenticationFactory.GetAuthenticationProvider("DbAuthenticationProviderName"); NamePasswordCredential credentials = new NamePasswordCredential(username, password); IIdentity identity; bool retVal = IAuthProvider.Authenticate(credentials, out identity); Assert.IsTrue(retVal); Assert.IsNotNull(identity); Assert.AreEqual(username, identity.Name); Assert.IsTrue(identity.IsAuthenticated); }
public bool Authenticate(HttpContext context, out HttpAuthenticationRequest request) { if (context.Request.Headers.TryGetValue("authorization", out var values) && values.Count == 1 && AuthenticationHeaderValue.TryParse(values[0], out var authenticationHeader) && authenticationHeader.Scheme == "Basic" && TryDecodeCredential(authenticationHeader.Parameter, out var username, out var password)) { request = new HttpAuthenticationRequest(context, username, password); _internalAuthenticationProvider.Authenticate(request); return(true); } request = null; return(false); }
public LoginToken Authenticate(string user, string pass) { IAuthenticationProvider authProv = AuthenticationManager.Instance.GetProvider(ctx); IUserIdentity uId = authProv.Authenticate(new UserPasswordCredential(user, pass)); if (uId != null && !Guid.Empty.Equals(uId.Uid)) { LoginToken token = new LoginToken(AuthenticationProviders.Instance.Local, Guid.NewGuid()); activeTokens.Add(token.Token, new LoginToken(token.Token, uId.Uid)); return(token); } return(null); }
public async Task <IActionResult> CompleteAuthentication(string sessionId) { ProviderInstance providerInstance = null; CreateAuthenicatedSession createSession = HttpContext.Session.GetObject <CreateAuthenicatedSession>(AUTHENTICATED_SESSION_KEY); if (createSession != null) { Provider provider = await providerRepository.Get(createSession.Base.AuthenticationProvider); providerInstance = await providerMappingService.CreateProviderInstance(provider, createSession.ProviderInstance); } //else if (id > 0) //{ // redirectId = id.ToString(); //} if (providerInstance == null) { return(RedirectToAction("Index", "Home")); } IAuthenticationProvider <object> authenticationProvider = await providerMappingService.CreateProvider <IAuthenticationProvider <object> >(providerInstance); try { //authenticationProvider.Initialize($"http://{Request.Host}/Authentication/CompleteAuthentication?sessionId={sessionId}", data => StoreSession(providerInstance.ID, data)); authenticationProvider.Initialize($"http://{Request.Host}/Authentication/CompleteAuthentication", data => StoreSession(providerInstance.ID, data)); bool result = await authenticationProvider.Authenticate(Request.Query.ToDictionary(k => k.Key, v => v.Value.ToString())); if (result && createSession != null) { // refresh the object createSession = HttpContext.Session.GetObject <CreateAuthenicatedSession>(AUTHENTICATED_SESSION_KEY); byte[] encryptedSessionData = await encryptionService.Encrypt(createSession.SessionData); await authenticatedSessionRepository.Add(createSession.Base.Name, encryptedSessionData, providerInstance); HttpContext.Session.Clear(); } } catch (Exception ex) { logger.LogError(ex, $"Failed to complete authentication for '{createSession.Base.Name}'"); } return(RedirectToAction("Index")); }
public ActionResult Login(LoginViewModel loginViewModel, string returnUrl) { if (ModelState.IsValid) { bool authenticated = _authenticationProvider.Authenticate(loginViewModel.UserName, loginViewModel.Password); if (authenticated) { return(Redirect(returnUrl ?? Url.Action("Index", "Admin"))); } ModelState.AddModelError("login", "Incorrect username or password"); TempData["message"] = "Incorrect username or password"; return(View()); } return(View()); }
public bool LogIn(Guid sessionId, ICredential cred) { if (cred != null) { ModuleRuntimeSession session = SessionProvider.Get(sessionId) as ModuleRuntimeSession; if (session != null) { IUserIdentity user = AuthenticationProvider.Authenticate(cred); if (user != null) { session.SetUserBinding(Guid.Empty, session.Binding); return(SessionProvider.Update(session)); } } } return(false); }
public Token Authenticate([FromBody] AuthenticationRequest request) { var token = _authProvider.Authenticate(request.Login, request.Password); if (token == null) { throw new CustomAuthenticationException(request.Login); } var sasToken = _infrastructure.CreateStorageSASToken(4); if (sasToken != null) { token.Values.Add(sasToken); } return(token); }
private AuthenticateResult ValidateToken(string code) { var token = _authenticationProvider.Authenticate(code); if (token == null || !token.IsValid()) { return(Unauthorized()); } var identity = new ApiIdentity(token); var principal = new GenericPrincipal(identity, token.Roles); var ticket = new AuthenticationTicket(principal, Scheme.Name); _httpContextAccessor.HttpContext.User = principal; _httpContextAccessor.HttpContext.User.AddIdentity(identity); return(AuthenticateResult.Success(ticket)); }
/// <summary> /// Call the authentication API to validate user credentials present in the request digest /// </summary> /// <returns>The <see cref="AuthenticatedToken"/>.</returns> private AuthenticatedToken AuthenticateUser() { if (reqInfo == null) { return(null); } DigestSecurityToken userToken = new DigestSecurityToken(reqInfo["response"], reqInfo["username"], reqInfo["nonce"], reqInfo["realm"], reqInfo["uri"], httpMethod, algoForDigest, algoForChecksum); AuthenticatedToken token = provider.Authenticate(userToken); return(token); }
public async Task ProcessAsync(HttpRequest httpRequest, HttpResponse httpResponse, IBot bot, CancellationToken cancellationToken = default(CancellationToken)) { if (httpRequest == null) { throw new ArgumentNullException(nameof(httpRequest)); } if (httpResponse == null) { throw new ArgumentNullException(nameof(httpResponse)); } if (bot == null) { throw new ArgumentNullException(nameof(bot)); } if (_authenticationProvider != null) { var authenticated = _authenticationProvider.Authenticate(httpRequest.Headers["Authorization"]); if (!authenticated) { httpResponse.StatusCode = (int)HttpStatusCode.Unauthorized; return; } } // deserialize the incoming Activity var activity = ReadRequest(httpRequest); var cancellationTokenSource = new CancellationTokenSource(); _botTelemetryClient.TrackTrace($"SkillHttpAdapter: Processing incoming activity. Activity id: {activity.Id}", Severity.Information, null); // process the inbound activity with the bot var invokeResponse = await _skillHttpBotAdapter.ProcessActivityAsync(activity, bot.OnTurnAsync, cancellationTokenSource.Token).ConfigureAwait(false); // trigger cancel token after activity is handled. this will stop the typing indicator cancellationTokenSource.Cancel(); // write the response, potentially serializing the InvokeResponse WriteResponse(httpResponse, invokeResponse); }
public ActionResult Login(LoginViewModel viewModel, String returnUrl) { if (ModelState.IsValid) { if (m_authenticationProvider.Authenticate(viewModel.UserName, viewModel.Password)) { return(Redirect(returnUrl ?? Url.Action("Index", "Admin"))); } else { ModelState.AddModelError("", "Incorrect username or password"); return(View()); } } else { return(View()); } }
public ActionResult Login(LoginViewModel login, string returnUrl) { if (ModelState.IsValid) { if (authProvider.Authenticate(login.Username, login.Password)) { return(Redirect(returnUrl ?? Url.Action("Index", "Admin"))); } else { ModelState.AddModelError("", "Incorrect username and password"); return(View()); } } else { return(View()); } }
/// <summary> /// Authenticates using the guest credentials. /// </summary> /// <param name="provider">The provider.</param> /// <returns>The authentication token.</returns> private static AuthenticatedToken AuthenticateGuest(IAuthenticationProvider provider) { if (provider == null) { return(null); } //Read guest credentials from config settings. string guestUserName = UserManager.GuestUserName; string guestPassword = Constants.GuestPassword; if (!string.IsNullOrEmpty(guestUserName) && !string.IsNullOrEmpty(guestPassword)) { //Authenticate guest UserNameSecurityToken guestCredentials = new UserNameSecurityToken(guestUserName, guestPassword); AuthenticatedToken guestToken = provider.Authenticate(guestCredentials); return(guestToken); } return(null); }
public LoginResponse Post([FromBody] LoginRequest request) { LoginResponse response = authenticationProvider.Authenticate(request); if (response.Result != Entities.UserManagement.LoginResultEnum.Successful) { throw new JMException(response.Result.ToString()); } else { //issue token response.Token = tokenProvider.IssueToken(request.Username.ToPlainString()); Context context = contextProvider.GetContext(); context.User = response.User; contextProvider.SetContext(context); } return(response); }
public static void PublishWithAuthentication( this IPublisher publisher, IAuthenticationProvider authenticationProvider, UserCredentials userCredentials, Action <Exception> setException, Func <ClaimsPrincipal, Message> onUser) { if (userCredentials == null) { var message = onUser(null); publisher.Publish(message); return; } authenticationProvider.Authenticate(new EmbeddedAuthenticationRequest(userCredentials.Username, userCredentials.Password, setException, user => { var message = onUser(user); publisher.Publish(message); })); }
public void Login(SignInOptions signInOptions) { var credential = new NetworkCredential(signInOptions.Username, signInOptions.Password, signInOptions.Domain); AuthenticationResult result = authenticationProvider.Authenticate(credential); if (result.Status == AuthenticationStatus.Failure) { throw new AuthenticationException(result.Status, Translation.Instance.Authentication_Failed); } if (result.Status == AuthenticationStatus.ServiceUnavailable) { throw new AuthenticationException(result.Status, Translation.Instance.Authentication_ServiceUnavailable); } var optionsFactory = new LoginOptionsFactory(settings, result.UserDetails, signInOptions); LoginOptions clientOptions = optionsFactory.CreateInstance(); client.Login(clientOptions); }
public async Task <ClaimsIdentity> Authenticate(HttpRequest httpRequest, HttpResponse httpResponse) { if (httpRequest == null) { throw new ArgumentNullException(nameof(httpRequest)); } if (httpResponse == null) { throw new ArgumentNullException(nameof(httpResponse)); } var authorizationHeader = httpRequest.Headers["Authorization"]; if (string.IsNullOrWhiteSpace(authorizationHeader)) { httpResponse.StatusCode = (int)HttpStatusCode.Unauthorized; return(null); } var claimsIdentity = _authenticationProvider.Authenticate(authorizationHeader); if (claimsIdentity == null) { httpResponse.StatusCode = (int)HttpStatusCode.Unauthorized; return(null); } var appIdClaimName = AuthHelpers.GetAppIdClaimName(claimsIdentity); var appId = claimsIdentity.Claims.FirstOrDefault(c => c.Type == appIdClaimName)?.Value; if (_whitelistAuthenticationProvider.AppsWhitelist != null && _whitelistAuthenticationProvider.AppsWhitelist.Count > 0 && !_whitelistAuthenticationProvider.AppsWhitelist.Contains(appId)) { httpResponse.StatusCode = (int)HttpStatusCode.Unauthorized; await httpResponse.WriteAsync("Skill could not allow access from calling bot.").ConfigureAwait(false); } return(claimsIdentity); }
public static void PublishWithAuthentication( this IPublisher publisher, IAuthenticationProvider authenticationProvider, UserCredentials userCredentials, Action<Exception> setException, Func<IPrincipal, Message> onUser) { if (userCredentials == null) { var message = onUser(null); publisher.Publish(message); return; } authenticationProvider.Authenticate(new EmbeddedAuthenticationRequest(userCredentials.Username, userCredentials.Password, setException, user => { var message = onUser(user); publisher.Publish(message); })); }