简体   繁体   English

Play Framework 2 Java可选身份验证

[英]Play Framework 2 Java Optional authentication

I have been playing around with authentication. 我一直在玩认证。 I want to be able to have some extra functions on certain pages available for those who log in. The problem is that if I don't use the @Security.Authenticated(Secured.class) annotation for the controller class I cannot get the username from the session so I cannot check if the user is logged in or not. 我希望能够在某些页面上为登录用户提供一些额外的功能。问题是,如果我不对控制器类使用@Security.Authenticated(Secured.class)注释,则无法获取用户名从会话中进行,因此我无法检查用户是否已登录。

How should I go about this? 我应该怎么做? Should I make sure all pages are authenticated and then have some sort of a guest login that automatically gets used for those other sessions or is there a way to check if the user is logged in even on a class without the @Security.Authenticated(Secured.class) annotation. 我应该确保所有页面均已通过身份验证,然后具有某种来宾登录名,该访客登录名会自动用于其他会话,或者是否有办法检查用户是否即使在没有@Security.Authenticated(Secured.class)注释。

It would be great if someone could point me in the right direction, if there is a tutorial available that does this or just some guidance. 如果有人可以向我指出正确的方向,或者有可用的指导手册,或者只是一些指导,那就太好了。

You should do two things: 您应该做两件事:

  1. Prevent unauthenticated users from viewing the functionality in your template: 防止未经身份验证的用户查看模板中的功能:

     @if(session().containsKey(Secured.SESSION_AUTH_KEY)) { /* Your comment form */ } 
  2. Prevent unauthenticated users from accessing your action: 防止未经身份验证的用户访问您的操作:

     @Security.Authenticated(Secured.class) public static Result submitComment() { ... } 

With: 带有:

public class Secured extends Security.Authenticator {

    public static final String SESSION_AUTH_KEY = "email";

    public String getUsername(Http.Context context) {
        return context.session().get(SESSION_AUTH_KEY);
    }

    public Result onUnauthorized(Http.Context context) {
        ...
    }
}

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

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