17.4 C
London
Tuesday, September 3, 2024

swift – JWT Authentication in iOS


I’m performing JWT authentication in my iOS app towards an ExpressJS server. The issue I’m having is discovering out on the consumer aspect about the kind of error that occurred on the server. Like was the token expired vs username/password was incorrect and many others. Server returns 400 with a message typically. However message is straightforward string sort.

Right here is a part of the server’s code:

exports.login = async (req, res) => {

    const { e mail, password } = req.physique
    const errors = validationResult(req)

    if (!errors.isEmpty()) {
        res.standing(400).json({ success: false, message: errors.array().map(error => error.msg).be part of(' ') })
        return
    }

    // verify if the person exists 
    const person = await fashions.Consumer.findOne({
        the place: {
            e mail: e mail
        }
    })

    if (person) {
        // verify the password 
        let outcome = await bcrypt.examine(password, person.password)
        if (outcome) {
            // generate the expiration time = 1 hour 
            const expirationTime = Math.flooring(Date.now() / 1000) + 3600;
            // generate the jwt token 
            const token = jwt.signal({ userId: person.id, exp: expirationTime }, course of.env.JWT_PRIVATE_KEY)
            res.json({ success: true, token: token, exp: expirationTime, roleId: person.roleId })

        } else {
            res.standing(400).json({ success: false, message: 'Incorrect password' })
        }

    } else {
        res.standing(400).json({ success: false, message: 'Consumer not discovered' })
        return
    }

}

The HTTPClient appears like the next. It is a generic HTTPClient used all through the consumer (SwiftUI). That is NOT the whole implementation however simply small a part of the HTTPClient.

let (information, response) = strive await session.information(for: request)
        
        guard let _ = response as? HTTPURLResponse else {
                throw NetworkError.invalidResponse
        }
    
        
        do {
            let outcome = strive JSONDecoder().decode(useful resource.modelType, from: information)
            return outcome
        } catch {
            throw NetworkError.decodingError(error)
        }

So, my query is that how can the consumer know what sort of error occurred because the server is just returning standing code, success and a message.

Latest news
Related news

LEAVE A REPLY

Please enter your comment!
Please enter your name here