Dropwizard Auth - 如果没有给出标题,如何返回默认用户?

时间:2016-04-07 22:48:58

标签: java authentication dropwizard

如果未指定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.

我怎样才能让它发挥作用?

1 个答案:

答案 0 :(得分:2)

因此,如果没有Basic Auth标头,则会将空BasicCredentials传递给预身份验证过程,从而导致自动未经授权的错误响应。所以我们需要确保有一个标题。为此,您可以注册在Dropwizard身份验证过滤器之前执行的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);

注册它