Java 播放框架基本身份验证用户在会话之间不更改

Java 播放框架基本身份验证用户在会话之间不更改,java,playframework,playframework-2.0,basic-authentication,Java,Playframework,Playframework 2.0,Basic Authentication,我正在尝试用play框架实现Basic Auth public class BasicAuth extends Action.Simple { private static final String REALM = "Authorisation Needed"; private static final String AUTHORISATION = "authorization"; private static final String WWW_AUTHENTICATE

我正在尝试用play框架实现Basic Auth

public class BasicAuth extends Action.Simple {

    private static final String REALM = "Authorisation Needed";
    private static final String AUTHORISATION = "authorization";
    private static final String WWW_AUTHENTICATE = "WWW-Authenticate";

    private static final F.Promise<Result> UNAUTHORISED = F.Promise.pure((Result) unauthorized());

    @Override
    public F.Promise<Result> call(Http.Context context) throws Throwable {
        Optional<String> auth_header = Optional.ofNullable(context.request().getHeader(AUTHORISATION));

        if (!auth_header.isPresent()) {
            context.response().setHeader(WWW_AUTHENTICATE, REALM);
            return UNAUTHORISED;
        }

        String encoded_credentials = auth_header.get().substring(6);
        byte[] decoded_credentials = Base64.getDecoder().decode(encoded_credentials);
        String[] credentials = new String(decoded_credentials, "UTF-8").split(":");

        if (credentials == null || credentials.length != 2) {
            return UNAUTHORISED;
        }

        User user = authorise(credentials);

        if (user == null) {
            return UNAUTHORISED;
        }

        context.session().put("email", user.getEmail());

        return delegate.call(context);
    }

    private User authorise(String[] credentials) {
        String username = credentials[0];
        String password = credentials[1];
        return User.find.where().eq("email", username).eq("password", password).findUnique();
    }

}

我真的需要解决这个问题。有什么帮助吗?

您正在使用哪个播放版本和哪个客户端/浏览器进行测试?我用play 2.4尝试了你的BasicAuth课程,尽管不得不将
领域
更改为
“基本领域=\“需要授权”
一切都按预期进行。我在浏览器中检查了Cookie,登录控制器的用户始终显示了正确的用户名:
@With(BasicAuth.class)public Result index(){Logger.info(“用户名:{}”,session().get(“电子邮件”);返回ok(index.render(“新应用程序准备就绪”);}
我正在使用play 2.4。我正在Mac上本地运行它。这会导致问题吗?您试图查找
已登录用户的
行中的
上下文
对象来自哪里?在Play 2.4中,您可以通过
session()
直接访问控制器中的会话。上下文来自Http.context。我无法让它工作,我尝试使用会话上下文。所以我很无知。我认为这与我的本地主机设置有关。但我因此不得不改变框架。不过,谢谢你的帮助。
User logged_user = UserDao.findByEmail(context.session().get("email"));