如果未指定BacicAuth的标头,我希望我的授权机制返回默认用户。我试图这样做:

@Override
    public Optional<User> authenticate(final BasicCredentials basicCredentials) throws AuthenticationException {

        String email = basicCredentials.getUsername();
        String plaintextPassword = basicCredentials.getPassword();

        final Optional<User> user = Optional.of(userDao.getUserByEmail(email));

        if (user.isPresent()) {
            return user;
            }
        else {
            return Optional.of(defaultUser);
        }
    }


但是,以某种方式,当我没有适当的标头进行请求时,我仍然会收到401。

我该如何运作?

最佳答案

因此,如果没有基本身份验证标头,则将空BasicCredentials传递给预身份验证过程,这将导致自动的未授权错误响应。因此,我们需要确保有一个标题。为此,您可以注册在Dropwizard auth过滤器之前执行的Jersey过滤器。在那里,我们可以添加带有默认用户名和密码的标题。

import java.io.IOException;
import javax.annotation.Priority;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.HttpHeaders;
import org.glassfish.jersey.internal.util.Base64;

@Priority(Priorities.AUTHENTICATION - 100)
public class PreAuthenticationFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext request) throws IOException {
        boolean hasValidHeader = false;
        if (request.getHeaders().containsKey(HttpHeaders.AUTHORIZATION)) {
            final String header = request.getHeaderString(HttpHeaders.AUTHORIZATION);
            if (header.toLowerCase().startsWith("basic")) {
                hasValidHeader = true;
            }
        }
        if (!hasValidHeader) {
            final String defaultUser = "defaultUser";
            final String defaultPassword = "defaultPassword";
            final String base64 = Base64.encodeAsString(defaultUser + ":" + defaultPassword);
            request.getHeaders().putSingle(HttpHeaders.AUTHORIZATION, "Basic " + base64);
        }
    }
}


然后只需向DW env.jersey().register(PreAuthenticationFilter.class);注册

09-05 21:28