Vishwas
Vishwas

Reputation: 7067

How to implement security Authorization using scala and play?

I am using scala and play framework. I want to use play security Authorization in my app.

Previously I implemented it in project using java and play like following :

public class Secured extends Security.Authenticator {
    private static String EMAIL = "Email";
  private static String U_COOKIE = "ucookie";
    public String getUsername(Context ctx) {
        String decodedText = null;
        String CHARSET = "ISO-8859-1";
        Cookies cookies = play.mvc.Controller.request().cookies();
        try {
            Cookie emailCookie = cookies.get(EMAIL);
      Cookie uCookie = cookies.get(U_COOKIE);
      if (uCookie !=null && uCookie.value() != null) {
    String userId = uCookie.value();
      }
            if (emailCookie != null && emailCookie.value() != null) {
                String email = emailCookie.value();
                try {
                    decodedText = new String(Base64.decodeBase64(email.getBytes(CHARSET)));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            Logger.error(e.getMessage());
        }
        return decodedText;
    }

    public Result onUnauthorized(Context ctx) {
        String done = play.mvc.Controller.request().path();
        return redirect(routes.RegController.signIn(done));
    }
}

and I used above Authorization in all of my method using

@Security.Authenticated(Secured.class)

Before any of my methods throughout my application.

When I call any method @before that method gives call to secured class and authenticate user.

Now I want to implement same thing using scala. Following are my questions....

1) Is it possible to use @ to inherit and call methods of secured class??

2) What is the right method to call play's security authentication??

P.S. I want to use cookies for implementation of security Authentication/Authorization.

Any help or workaround will be great favor..

Upvotes: 3

Views: 3463

Answers (1)

Andreas Neumann
Andreas Neumann

Reputation: 10894

If you build an application intended for production: Don't do it

Use one of the many frameworks out there:

They are also a great starting point to look for best practices.

If you want to do it mainly for learning and there are no real scecurity concerns go for:

https://www.playframework.com/documentation/2.3.x/ScalaActionsComposition

There look for the heading auth it gives some information how to do it.

To have the authentication kick in before any method you could use a Filter to intercept the request:

https://www.playframework.com/documentation/2.3.x/ScalaInterceptors

Upvotes: 10

Related Questions