/// <inheritdoc/> public void SendVerificationToken(TokenInfoDto verificationTokenInfo) { string name = verificationTokenInfo.Name; string emailAddress = verificationTokenInfo.EmailAddress; string verificationToken = verificationTokenInfo.Token; string subjectOfTheMessage = verificationTokenInfo.Subject; string bodyOfTheMessage = verificationTokenInfo.Body; MailTemplate mt = new MailTemplate(); mt.SetReceiver(name, emailAddress); mt.SetMessage(subjectOfTheMessage, bodyOfTheMessage + ": " + verificationToken); try { mt.Send(); } catch (SocketException socketException) { _logger.Fatal("MailingService.cs: An error related to the socket occured while " + "trying to send the email. Check the credentials for " + "sending the email. Method Send, line 40", socketException); } catch (ProtocolException protocolException) { _logger.Fatal("MailingService.cs: An error related with the protocol occured while " + "trying to send the email. Check that you are using a valid " + "protocol for sending the emails.", protocolException); } }
public bool LogOutWithToken(TokenInfoDto tokenInfo) { if (tokenInfo != null) { return(AuthenticationBL.LogOutWithToken(tokenInfo.Token)); } return(false); }
private TokenInfoDto GenerateTokenForRefreshToken(AskTokenDto tokenInfo, IStringLocalizer errorLocal) { TokenInfoDto toReturn = null; if (String.IsNullOrWhiteSpace(tokenInfo.ClientPublicId)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameRefreshToken, Description = errorLocal["RefreshTokenParameterError"] }; } using (var context = RepositoriesFactory.CreateContext()) { var clientRepo = RepositoriesFactory.GetClientRepository(context); var myClient = clientRepo.GetByPublicId(tokenInfo.ClientPublicId); if (!CheckIfClientsCredentialsAreValid(myClient, tokenInfo.AuthorizationHeader)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameUnauthorizedClient, Description = errorLocal["UnauthorizedClient"] }; } var tokenDetail = JwtService.ExtractToken(new ExtractTokenDto() { Token = tokenInfo.RefreshToken, TokenName = OAuthConvention.RefreshToken }); if (!CheckIfTokenIsValid(tokenDetail, context)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameInvalidGrant, Description = errorLocal["RefreshTokenInvalid"] }; } if (!CheckIfScopesAreAuthorizedForClient(tokenDetail.ClientId, tokenInfo.Scope)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameInvalidScope, Description = errorLocal["UnauthorizedScope"] }; } toReturn = GenerateAccessTokenAndUpdateRefreshToken(tokenInfo, context, tokenDetail.UserName); context.Commit(); } return(toReturn); }
private void SendRecoveryToken() { TokenInfoDto recoveryToken = new TokenInfoDto() { Name = _username, EmailAddress = _emailAddress, Token = _verificationToken, Subject = Properties.Langs.Resources.PasswordRecovery, Body = Properties.Langs.Resources.RecoveryToken }; TokenManager.SendToken(recoveryToken); }
private void SendActivationToken() { TokenInfoDto verificationTokenInfo = new TokenInfoDto() { Name = _username, EmailAddress = _emailAddress, Token = _verificationToken, Subject = Properties.Langs.Resources.Welcome, Body = Properties.Langs.Resources.VerificationToken }; TokenManager.SendToken(verificationTokenInfo); }
private TokenInfoDto GenerateTokenForClientCredentailsGrant(AskTokenDto tokenInfo, IStringLocalizer errorLocal) { TokenInfoDto toReturn = null; using (var context = RepositoriesFactory.CreateContext()) { var clientRepo = RepositoriesFactory.GetClientRepository(context); var myClient = clientRepo.GetByPublicId(tokenInfo.ClientPublicId); if (!CheckIfClientsCredentialsAreValid(myClient, tokenInfo.AuthorizationHeader)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameUnauthorizedClient, Description = errorLocal["UnauthorizedClient"] }; } if (!CheckIfScopesAreAuthorizedForClient(myClient.PublicId, tokenInfo.Scope)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameInvalidScope, Description = errorLocal["UnauthorizedScope"] }; } var accesToken = JwtService.GenerateToken(new CreateTokenDto() { ClientPublicId = myClient.PublicId, Scope = tokenInfo.Scope, SecondsLifeTime = Configuration.AccesTokenLifeTimeInSeconds, TokenName = OAuthConvention.AccessToken, UserName = String.Empty }); toReturn = new TokenInfoDto() { AccessToken = accesToken.Token, ExpireIn = Configuration.AccesTokenLifeTimeInSeconds, Scope = tokenInfo.Scope, TokenType = OAuthConvention.AccessToken }; } return(toReturn); }
public async Task <ResponseAuthDto> Authenticate(LoginDto model, string ipAddress = "") { var user = await this.unitOfWork.Users.GetUserByEmailAsync(model.username); if (user == null) { throw new AppException("User not found - Invalid Email"); } if (user.password_hash == Helper.HashPassword(model.password, user.password_salt)) { throw new AppException("Invalid password"); } var userInfo = _mapper.Map <UserInfo>(user); TokenDto newAccessToken = tokenService.generateAccessToken(userInfo); TokenDto newRefreshToken = tokenService.generateRefreshToken(userInfo); var token = new UserTokenData() { AccessToken = newAccessToken.EncodedToken, RefreshToken = newRefreshToken.EncodedToken, BlackListed = false, AccessTokenExpiresAt = newRefreshToken.TokenModel.ValidTo, CreatedAt = newRefreshToken.TokenModel.IssuedAt, CreatedByIP = ipAddress, }; token.user_id = user.user_id; await this.unitOfWork.Users.AddRefreshTokenAsync(token); var tokenInfo = new TokenInfoDto { AccessToken = newAccessToken.EncodedToken, RefreshToken = newRefreshToken.EncodedToken, ExpiresAt = newRefreshToken.TokenModel.ValidTo, TokenType = JwtBearerDefaults.AuthenticationScheme }; return(new ResponseAuthDto { Token = tokenInfo, User = userInfo }); }
public TokenInfoDto LoginWithUserName(UserDto loginInfo) { TokenInfoDto sessionDto = new TokenInfoDto(); if (loginInfo.UserName != null && loginInfo.Password != null) { var userSession = AuthenticationBL.LoginWithUserName(loginInfo.UserName, loginInfo.Password); if (userSession != null) { sessionDto.Role = userSession.User.Role; sessionDto.UserId = userSession.User.Id; sessionDto.UserName = userSession.User.UserName; sessionDto.Token = userSession.Token; return(sessionDto); } } return(null); }
public TokenInfoDto GenerateToken(AskTokenDto tokenInfo) { Logger.LogInformation("Ask for token"); Validate(tokenInfo); var errorLocal = GetErrorStringLocalizer(); TokenInfoDto result = null; switch (tokenInfo.GrantType) { case OAuthConvention.GrantTypeAuthorizationCode: result = GenerateTokenForAuthorizationCodeGrant(tokenInfo, errorLocal); break; case OAuthConvention.GrantTypeRefreshToken: result = GenerateTokenForRefreshToken(tokenInfo, errorLocal); break; case OAuthConvention.GrantTypePassword: result = GenerateTokenForPasswordGrant(tokenInfo, errorLocal); break; case OAuthConvention.GrantTypeClientCredentials: result = GenerateTokenForClientCredentailsGrant(tokenInfo, errorLocal); break; default: throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameUnsupportedGrantType, Description = errorLocal["UnsupportedGrantType"] }; } return(result); }
private TokenInfoDto GenerateAccessTokenAndUpdateRefreshToken(AskTokenDto tokenInfo, IContext context, string userName) { TokenInfoDto toReturn; var newRefreshToken = JwtService.GenerateToken(new CreateTokenDto() { ClientPublicId = tokenInfo.ClientPublicId, Scope = tokenInfo.Scope, SecondsLifeTime = Configuration.RefreshTokenLifeTimeInSeconds, TokenName = OAuthConvention.RefreshToken, UserName = userName }); var accesToken = JwtService.GenerateToken(new CreateTokenDto() { ClientPublicId = tokenInfo.ClientPublicId, Scope = tokenInfo.Scope, SecondsLifeTime = Configuration.AccesTokenLifeTimeInSeconds, TokenName = OAuthConvention.AccessToken, UserName = userName }); var userClientRepo = RepositoriesFactory.GetUserClientRepository(context); var myUc = userClientRepo.GetUserClientByClientPublicIdAndUserName(tokenInfo.ClientPublicId, userName); myUc.RefreshToken = newRefreshToken.Token; userClientRepo.Update(myUc); toReturn = new TokenInfoDto() { AccessToken = accesToken.Token, ExpireIn = Configuration.AccesTokenLifeTimeInSeconds, RefreshToken = newRefreshToken.Token, Scope = tokenInfo.Scope, TokenType = OAuthConvention.AccessToken }; return(toReturn); }
private void SendNewCode() { string newToken = TokenManager.GenerateToken(); bool newVerificationTokenWasAssigned = false; if (newToken != "") { AccountVerificationServiceClient accountVerificationServiceClient = new AccountVerificationServiceClient(); newVerificationTokenWasAssigned = accountVerificationServiceClient.AssignNewRecoveryToken(_emailAddress, newToken); } if (newVerificationTokenWasAssigned) { TokenInfoDto verificationTokenInfo = new TokenInfoDto() { Name = _username, EmailAddress = _emailAddress, Token = newToken }; TokenManager.SendToken(verificationTokenInfo); MessageBox.Show(Properties.Langs.Resources.NewCodeSentMessage); } }
public async Task <ResponseAuthDto> RenewAccessToken(RequestAuthDto request, string ipAddress = "") { JwtSecurityToken decodedToken = this.tokenService.decodeToken(request.RefreshToken); var user = await this.unitOfWork.Users.GetByIdAsync(int.Parse(decodedToken.Subject)); if (user == null) { throw new AppException("Invalid token."); } var tokenRecord = await this.unitOfWork.Users.GetUserRefreshToken(request.RefreshToken); if (tokenRecord == null) { throw new AppException("Invalid refresh token."); } //Access token should be verified. //because on the token storage it's been save as a paired token (access and refresh token are saved together) if (tokenRecord.AccessToken != request.AccessToken) { throw new AppException("Invalid access token."); } if (tokenRecord.BlackListed) { throw new AppException("Token is blacklisted."); } if (tokenRecord.ExpiresAt.Subtract(DateTime.UtcNow).TotalSeconds <= 0) { throw new AppException("Refresh token is expired."); } //AutoMapper.Mapper.Map<Destination>(source); var userInfo = _mapper.Map <UserInfo>(user); TokenDto newAccessToken = tokenService.generateAccessToken(userInfo); TokenDto newRefreshToken = tokenService.generateRefreshToken(userInfo); await this.unitOfWork.Users.BlackListed(tokenRecord.TokenId); var token = new UserTokenData() { AccessToken = newAccessToken.EncodedToken, RefreshToken = newRefreshToken.EncodedToken, BlackListed = false, ExpiresAt = newRefreshToken.TokenModel.ValidTo, CreatedAt = newRefreshToken.TokenModel.IssuedAt, CreatedByIP = ipAddress }; await this.unitOfWork.Users.AddRefreshTokenAsync(token); var tokenInfo = new TokenInfoDto { AccessToken = newAccessToken.EncodedToken, RefreshToken = newRefreshToken.EncodedToken, ExpiresAt = newRefreshToken.TokenModel.ValidTo, TokenType = JwtBearerDefaults.AuthenticationScheme }; return(new ResponseAuthDto { Token = tokenInfo, User = userInfo }); }
private TokenInfoDto GenerateTokenForPasswordGrant(AskTokenDto tokenInfo, IStringLocalizer errorLocal) { TokenInfoDto toReturn = null; if (String.IsNullOrWhiteSpace(tokenInfo.ParameterUsername)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameInvalidRequest, Description = errorLocal["UserNameParameterError"] }; } if (String.IsNullOrWhiteSpace(tokenInfo.Password)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameInvalidRequest, Description = errorLocal["PasswordParameterError"] }; } using (var context = RepositoriesFactory.CreateContext()) { var clientRepo = RepositoriesFactory.GetClientRepository(context); var myClient = clientRepo.GetByPublicId(tokenInfo.ClientPublicId); if (!CheckIfClientsCredentialsAreValid(myClient, tokenInfo.AuthorizationHeader)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameUnauthorizedClient, Description = errorLocal["UnauthorizedClient"] }; } var repo = RepositoriesFactory.GetUserRepository(context); var user = repo.GetByUserName(tokenInfo.ParameterUsername); if (user == null || !user.IsValid || !EncryptonService.AreEqualsSha256( String.Concat(Configuration.PasswordSalt, tokenInfo.Password), user.Password)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameInvalidGrant, Description = errorLocal["UserCredentialsIncorrects"] }; } if (!CheckIfScopesAreAuthorizedForClient(myClient.PublicId, tokenInfo.Scope)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameInvalidScope, Description = errorLocal["UnauthorizedScope"] }; } toReturn = GenerateAccessTokenAndUpdateRefreshToken(tokenInfo, context, tokenInfo.ParameterUsername); context.Commit(); } return(toReturn); }
private TokenInfoDto GenerateTokenForAuthorizationCodeGrant(AskTokenDto tokenInfo, IStringLocalizer errorLocal) { TokenInfoDto toReturn = null; if (String.IsNullOrWhiteSpace(tokenInfo.ClientPublicId)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameInvalidRequest, Description = errorLocal["ClientIdParameterError"] }; } using (var context = RepositoriesFactory.CreateContext()) { var clientRepo = RepositoriesFactory.GetClientRepository(context); var myClient = clientRepo.GetByPublicId(tokenInfo.ClientPublicId); if (!CheckIfClientsCredentialsAreValid(myClient, tokenInfo.AuthorizationHeader)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameUnauthorizedClient, Description = errorLocal["UnauthorizedClient"] }; } if (String.IsNullOrWhiteSpace(tokenInfo.CodeValue)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameInvalidRequest, Description = errorLocal["CodeParameterError"] }; } if (String.IsNullOrWhiteSpace(tokenInfo.RedirectUrl) || !Uri.TryCreate(tokenInfo.RedirectUrl, UriKind.Absolute, out var myUri)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameInvalidRequest, Description = errorLocal["ReturnUrlParameterError"] }; } if (!CheckIfClientValidForToken(myClient, tokenInfo.RedirectUrl, OAuthConvention.ResponseTypeCode)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameInvalidClient, Description = errorLocal["AskTokenInvalidClient"] }; } if (!CheckIfCodeIsValid(tokenInfo.ClientPublicId, tokenInfo.Scope, tokenInfo.CodeValue, context, out var userName)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameInvalidGrant, Description = errorLocal["AskTokenInvalidGrant"] }; } toReturn = GenerateAccessTokenAndUpdateRefreshToken(tokenInfo, context, userName); context.Commit(); } return(toReturn); }
/// <summary> /// Sends the token to the specified user. /// </summary> /// <param name="tokenInfo"> /// The <c>TokenInfo</c> object which contains the /// necessary info to send the token. /// </param> public static void SendToken(TokenInfoDto tokenInfo) { MemoryGameService.MailingServiceClient client = new MemoryGameService.MailingServiceClient(); client.SendVerificationToken(tokenInfo); }