Reputation: 2178
I've recently started with vapor4 (didn't use any older version) and I'm trying to figure out how to implement user authorization and authentication. While i understand basic concepts, having worked with Laravel before I still can't figure out what to do in vapor.
I extended my User with. Ik there is no pw hashing, this is for testing and basic understanding. We'll ignore that for now.
extension User: ModelAuthenticatable
{
static let usernameKey = \User.$name
static let passwordHashKey = \User.$password
func verify(password: String) throws -> Bool {
return password == self.password
}
}
The problem is i can't find a tutorial how to use this authentication. I just kind of try stuff to get it to work, but to no success. This is in my routes file.
let auth = app.grouped(User.authenticator())
auth.get("sign-in") { req in
"I'm authenticated"
}
My first goal would just be to receive a success or failure answer when trying this route. Ultimately i want to switch to a token based solution but one step at a time.
stuff i read was: https://docs.vapor.codes/4.0/authentication/ and https://theswiftdev.com/all-about-authentication-in-vapor-4/. Anyway i couldn't quit figure it out how to use the described authenticators.
Upvotes: 4
Views: 1497
Reputation: 2178
While writing this i finally figured it out. Anyway for people stumbling on this. It's as easy as this:
let auth = app.grouped(User.authenticator(), User.guardMiddleware())
auth.get("sign-in") { req in
"I'm authenticated"
}
Your user-class offers a guardMiddleware
by default. You don't have to implement anything else, just use it in your route.
Upvotes: 4