Changing IsAuthenticated Playback Authentication Method

I would like to create my own authentication method for a Play2 Framework application. I try in Scala and play - and I'm new to both.

The zentask example has a function called IsAuthenticated in Secure Binding:

def IsAuthenticated(f: => String => Request[AnyContent] => Result) = Security.Authenticated(username, onUnauthorized) { user => Action(request => f(user)(request)) } 

This definition is rather complicated. I found several questions regarding the syntax of this definition in stackoverflow, but I'm still not sure how to change this.

I can verify authentication in User.authenticate through a database search. But the authentication I want to do does not use a database. I am not sure how and where to post in another type of authentication. Is Security.Authenticated () used to use the User class / object?

+4
source share
1 answer

Security.Authenticated simply checks if the session contains a "username". If so, the user must be authenticated.

You must authenticate your users yourself, by searching the database or by any other means. Then save the user ID (or email address or just a name) in the session:

 val user = // fetch user info Redirect("/").withSession("userId" → user.id.toString) 

Then wrap the action in a Security.Authenticated call:

 def someAction = Security.Authenticated( req => req.session.get("userId"), _ => Redirect(views.html.login())) { userId => Action { Ok(html.index()) } } 

The first Authenticated argument is a function that retrieves the user ID from the session. It returns Option[String] , i.e. Some[String] if the session has id or None if this does not happen.

 req => req.session.get("userId") 

The second argument is a function that returns Result for use if the session does not contain a user ID. Usually you need to redirect to the login page.

 _ => Redirect(views.html.login()) 

The final argument is a function that returns an Action . It is used if the user is authenticated.

 userId => Action { Ok(html.index()) } 

You are not required to use the implementation of the game, do not hesitate to wrap it in a convenient assistant or write it from scratch according to your needs:

 def myAuth(f: String => Result) = Security.Authenticated( req => req.session.get("userId"), _ => Redirect(views.html.login())) { userId => Action { f(userId) } } def someAction = myAuth { userId => Ok(html.index()) } 
+5
source

All Articles