简体   繁体   English

使用基本身份验证配置 Spring Boot 的嵌入式 tomcat 容器

[英]Configuring Spring Boot's embedded tomcat container with basic auth

I am using Spring Boot 1.5.7, without Spring Security.我使用的是 Spring Boot 1.5.7,没有Spring Security。 My objective is to experiment with the embedded tomcat container and enable basic authn.我的目标是试验嵌入式 tomcat 容器并启用基本身份验证。

Here is what I have:这是我所拥有的:

@Bean
public EmbeddedServletContainerFactory servletContainer() {
    final TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
    tomcat.addContextCustomizers(ctx -> {
        String AUTH_ROLE = "admin";
        LoginConfig config = new LoginConfig();
        config.setAuthMethod("BASIC");
        ctx.setLoginConfig(config);
        ctx.addSecurityRole(AUTH_ROLE);
        SecurityConstraint constraint = new SecurityConstraint();
        constraint.addAuthRole(AUTH_ROLE);
        SecurityCollection collection = new SecurityCollection();
        collection.addPattern("/*");
        constraint.addCollection(collection);
        ctx.addConstraint(constraint);
    });

    return tomcat;
}

This does not seem to have any effect.这似乎没有任何影响。 Is this sort of thing possible with Spring Boot programmatically, or could it only be done via the likes of web.xml?这种事情是否可以通过 Spring Boot 以编程方式实现,还是只能通过 web.xml 之类的方式完成?

PS: There are any number of posts on Stackoverflow detailing various solutions and alternatives that involve the Spring Security project. PS:Stackoverflow 上有很多帖子详细介绍了涉及 Spring Security 项目的各种解决方案和替代方案。 I should re-emphasize here that I would like to learn if there is a way to solve this without involving that library.我应该在这里再次强调,我想了解是否有办法在不涉及该库的情况下解决这个问题。

Your configuration is good, but you need to add a Basic authenticator valve to the factory: 您的配置很好,但是您需要在工厂中添加基本身份验证器阀:

 final TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
    tomcat.addContextValves(new BasicAuthenticator());
    tomcat.addContextCustomizers(....

@misagh moayyed, where do you have the users defined? @misagh moayyed,你在哪里定义了用户? I am trying to utilize embedded tomcat authentication and I do get the basic auth prompt but the credentials I pass are not valid.我正在尝试使用嵌入式 tomcat 身份验证,并且确实收到了基本身份验证提示,但我传递的凭据无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM