简体   繁体   English

Play Framework 2.4授权

[英]Play Framework 2.4 authorization

I have a class (Account) that represents the user's system. 我有一个代表用户系统的类(Account)。 Account contains a field role. 帐户包含字段角色。 It is the enum that contains three cases. 这是包含三个案例的枚举。 Account class 帐户类

public class Account extends Model {

@Id
@Email
public String email;

@Required
@NotNull
public String password;

@Required
@NotNull
public String firstName;

@Required
@NotNull
public String lastName;

@Required
public String phone;

public MyRole role;

MyRole 我的角色

public enum MyRole {

ADMIN,
TEACHER,
USER

}

How can I implement an authorization? 我如何实施授权?

I think you could use Deadbolt-2 library, listed in the Play Framework plugins . 我想你可以使用Play Framework插件中列出的Deadbolt-2库。

In the same idea of not reinvent the wheel, did you take a look at the Play-Authenticate plugin ? 在不重新发明轮子的想法中,您是否看过Play-Authenticate插件? An another advantage of this last one is that it is compatible with Deadbolt-2. 最后一个的另一个优点是它与Deadbolt-2兼容。

Deadbolt-2 library is a solution. Deadbolt-2库是一个解决方案。 However, if you want to build your very own one, firstly, you need to read https://www.playframework.com/documentation/2.4.x/ScalaActionsComposition . 但是,如果您想构建自己的,首先需要阅读https://www.playframework.com/documentation/2.4.x/ScalaActionsComposition

Actually, it is not that difficult and you can implement almost unlimited, very flexiable solution. 实际上,它并不困难,您可以实现几乎无限的,非常灵活的解决方案。

The basic idea is to define a UserAuthAction, like: 基本思想是定义UserAuthAction,如:

@Singleton
class UserAuthAction @Inject() (principalService: PrincipalService) extends ActionBuilder[Request] with ActionFilter[Request] {
  override protected def filter[A](request: Request[A]) = Future.successful {
    request.session.get(principalService.accessTokenCacheKey).map { accessToken =>
      if (principalService.authenticate(accessToken))
        None
      else
        Some(Results.Redirect(routes.PrincipalController.login()))
    } getOrElse {
      Some(Results.Redirect(routes.PrincipalController.login()))
    }
  }
}

And then compose it with the actions the do the actually job. 然后用实际工作的动作来组合它。 For example: 例如:

@Singleton
class Application @Inject() (userAuthAction: UserAuthAction) extends Controller {
  def index = (userAuthAction andThen anyAction) { request =>
    Ok(views.html.index())
  }
}

Along the way, if you are using ActionRefiner, you can even extract additional user information and provide it to the latter actions, such as anyAction above. 在此过程中,如果您使用的是ActionRefiner,您甚至可以提取其他用户信息并将其提供给后面的操作,例如上面的anyAction。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM