public string Login(LoginCommand request) { string jwtToken = ""; var credential = request.Credential; credential.Password = GenerateSha256(credential.Password); try { var user = _credentialDataMapper.Find(x => x.Email.ToLower().CompareTo(credential.Email.ToLower()) == 0 && x.Password == credential.Password).FirstOrDefault(); if (user != null) { var roleList = new List <string>(); foreach (var role in user.CredentialRoles) { roleList.Add(role.Role.Name); } jwtToken = new JSONWebToken(user.Id, user.Email, roleList).Token; } } catch (Exception ex) { _logger.LogError("DB exception occured with email: {0}", credential?.Email); _logger.LogDebug( "DB exception occured with email {}, it threw exception: {}. Inner exception: {}", credential?.Email, ex.Message, ex.InnerException?.Message ); throw new DatabaseException("Something unexpected happened while searching through the database"); } return(jwtToken); }
public void Configure(IServiceCollection services, IConfiguration configuration, IWebHostEnvironment env) { var jsonWebToken = new JSONWebToken(); configuration.Bind(nameof(jsonWebToken), jsonWebToken); services.AddSingleton(jsonWebToken); var tokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey( Encoding.ASCII.GetBytes(jsonWebToken.Secret)), ValidateIssuer = false, ValidateAudience = false, RequireExpirationTime = false, ValidateLifetime = true }; services.AddSingleton(tokenValidationParameters); services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { options.SaveToken = true; options.TokenValidationParameters = tokenValidationParameters; }); }
/// <summary> /// Check if JWT is enabled and validate the JWT if required. /// If JWT is not enabled, authorization is granted if username & password are emtpy. /// </summary> private static void ValidateUserAndPassword(MqttConnectionValidatorContext mqttConnectionValidatorContext) { mqttConnectionValidatorContext.ReasonCode = MqttConnectReasonCode.Success; Logger.Info($"Connection from client '{mqttConnectionValidatorContext.ClientId}'"); bool validateJWT = true; if (string.IsNullOrEmpty(mqttConnectionValidatorContext.Username)) { validateJWT = false; Logger.Info("Connection request: username is null."); } else { Logger.Info($"Username: {mqttConnectionValidatorContext.Username}"); } if (string.IsNullOrEmpty(mqttConnectionValidatorContext.Password)) { validateJWT = false; Logger.Info("Connection request: username is null."); } else { Logger.Info($"Password: {mqttConnectionValidatorContext.Password}"); } if (validateJWT) { JSONWebToken tokenHandler = new JSONWebToken(); tokenHandler.IsValid(mqttConnectionValidatorContext.Password); } }
/// <summary> /// Retrieve user name and password for login for Mindsphere cloud service /// </summary> /// <param name="clientId">Client ID (publisher ID)</param> /// <param name="userName">out: user name string</param> /// <param name="password">out: password string</param> public override void GetUserNameAndPassword(string clientId, out string userName, out string password) { // UserName = "******" // Password = JWT JSONWebToken jwt = new JSONWebToken(); userName = "******"; password = jwt.CreateJWT(ClientCert, ClientCaChain, clientId); }
public void Validate_ShouldSucceed() { // Arrange var listener = new AccountListener(null, new LoggerFactory()); var jwt = new JSONWebToken(1, "*****@*****.**", new List <string>() { "Gebruikert" }); // Act var isValid = listener.Validate(new ValidateCommand(jwt.Token, "")); // Assert Assert.IsTrue(isValid); }
public void TestEncode() { var secret_key = "secret"; JSONWebToken jwt_object_01 = new JSONWebToken() { TokenData = new Data() { Header = new Dictionary <string, string>() { { "alg", "HS256" }, { "typ", "JWT" } }, Payload = new Dictionary <string, object>() { { "sub", 1234567890 }, { "name", "John Doe" }, { "admin", 1 }, { "jti", "e0e56504-0060-434a-aaae-fc07c69be912" }, { "iat", 1510316753 }, { "exp", 1510320353 }, }, }, Secret = secret_key, }; string jwt_token = jwt_object_01.Encode(); string token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9" + "." + "eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImp0aSI6ImUwZTU2NTA0LTAwNjAtNDM0YS1hYWFlLWZjMDdjNjliZTkxMiIsImlhdCI6MTUxMDMxNjc1MywiZXhwIjoxNTEwMzIwNDkxfQ" + "." + "gqArrrW1oO8x6PwTeD2kHuujfNvk4uNx9Zbf0FAkZy0" ; string json = jwt_object_01.Decode(token, secret_key); return; }
public GenerateTokenCommandHandler(ApiDataContext context, JSONWebToken jsonWebToken) { _context = context; _jsonWebToken = jsonWebToken; }