我试图用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();
}
}
但是用户不会在请求之间进行更改。即我在初始化服务器后使用Joe Bloggs登录,它将Joe作为当前用户返回。
下一个请求我使用Bill Gates登录,它返回Joe Bloggs作为当前用户。
我将以如下方式返回存储在控制器会话中的电子邮件:
User logged_user = UserDao.findByEmail(context.session().get("email"));
我真的需要解决这个问题。有什么帮助吗?