您始终可以实现身份验证器接口。
public class MyAuthenticator implements Authenticator {
@Override
public User authenticate(HttpServletRequest request) {
HttpSession session = request.getSession(false);
//
return null;// if not authenticated, otherwise return User object.
}
}
// Endpoints class.
@Api(name = "example", authenticators = { MyAuthenticator.class })
public class MyEndpoints {
public Profile getProfile(User user) {
if (user == null) {
throw new UnauthorizedException("Authorization required");
}
return new Profile(user.getEmail(), "displayName");
}
// store this class somewhere in models
public class Profile {
private String email;
private String displayName;
public Profile(String email, String displayName) {
this.email = email;
this.displayName = displayName;
}
public String getEmail() {
return email;
}
public String getdisplayName() {
return displayName;
}
}
}
使用 HttpServletRequest 对象来实现基于经典会话的登录或使用您自己的自定义标头。嗯,这取决于你的情况。未通过身份验证时返回 null,通过身份验证时返回 User 对象。还要在双方(客户端和服务器)上实施某种加密,以阻止拥有会话密钥的人访问您的 api。