1

我目前在我的应用程序中使用http://www.dropwizard.io/1.1.0/docs/manual/auth.html# Dropwizard-Authentication。但我喜欢“手动”进行身份验证,这意味着来自未经过身份验证的 REST 接口上的特定登录/注销 API 调用。

是否有可能将 REST 调用转发到身份验证?

@POST
@Path("login")
@Consumes(MediaType.APPLICATION_JSON)
@Timed
@UnitOfWork
public Optional<LoginResponse> login(LoginRequest request) {
    // TODO forward login request to authentication
    return null;
}

提前谢谢

4

1 回答 1

1

谢谢帮助我。我找到了这样的解决方案:

向 REST 客户端添加身份验证器

    client = ClientBuilder.newClient();
    authenticator = new Authenticator();
    client.register(authenticator);

在登录成功时设置身份验证器

    final UserAPIResponse response = create(request, UserAPI.PATH_ATTRIBUTE_DEFINITION_LOGIN);
    if (response == null || response.isFailed()) {
        connector.setupAuthenticator(null, null);
    } else {
        connector.setupAuthenticator(request.getUsername(), request.getPassword());
    }

这是身份验证器

class Authenticator implements ClientRequestFilter {

@Override
public void filter(ClientRequestContext requestContext) throws IOException {
    final MultivaluedMap<String, Object> headers = requestContext.getHeaders();
    final String basicAuthentication = getBasicAuthentication();
    if (basicAuthentication == null) return;
    headers.add("Authorization", basicAuthentication);

}

void setup(String username, String password) {
    this.user = username;
    this.password = password;
}

private String getBasicAuthentication() {
    if (user == null || password == null) return null;
    final String token = this.user + ":" + this.password;
    try {
        return "BASIC " + DatatypeConverter.printBase64Binary(token.getBytes("UTF-8"));
    } catch (final UnsupportedEncodingException ex) {
        throw new IllegalStateException("Cannot encode with UTF-8", ex);
    }
}

private String password;

private String user;

}

在服务器端我有一个身份验证器

public class UserAuthenticator implements Authenticator<BasicCredentials, User> {

UserAuthenticator(UserDAO userDAO) {
    this.userDAO = userDAO;
}

@UnitOfWork
@Override
public Optional<User> authenticate(BasicCredentials credentials) throws AuthenticationException {
    final String username = credentials.getUsername();
    final Optional<DbUser> result = userDAO.getByName(username);
    if (!result.isPresent()) return Optional.empty();

    final DbUser user = result.get();
    final String password = credentials.getPassword();
    if (!StringUtils.equals(password, user.getPassword())) return Optional.empty();

    if (!user.isOnline()) return Optional.empty();
    user.handleAction();
    userDAO.save(user);

    return Optional.of(UserMgr.convert(user));
}

private final UserDAO userDAO;

}

并让 em 正常工作:

SessionDao dao = new SessionDao(hibernateBundle.getSessionFactory());
ExampleAuthenticator exampleAuthenticator = new      UnitOfWorkAwareProxyFactory(hibernateBundle)
           .create(ExampleAuthenticator.class, SessionDao.class, dao);

所以最后有一个 REST-Call 来登录用户,并且客户端自动对结果进行身份验证。

于 2017-03-31T22:56:34.473 回答