【问题标题】:Spring Boot with container security具有容器安全性的 Spring Boot
【发布时间】:2014-11-21 18:51:43
【问题描述】:

我最近在一些项目中使用了 Spring Boot,我真的很喜欢它。对于一个新项目,我们想使用 tomcat-users.xml 进行真正的基本身份验证,但我不知道如何在没有 web.xml 文件的情况下使用该机制。大多数使用 Spring Boot 的人似乎都在使用 Spring Security。

是否可以在 Spring Boot Java 配置模型中使用 tomcat 容器安全性?我知道这打破了可运行的 jar 范例,但无论如何我们都计划将其部署为战争。

【问题讨论】:

  • stackoverflow.com/a/25999919/28214,这里有一个以编程方式配置用户的例子。
  • 这是关于以编程方式设置用户的重要信息,但它没有涵盖如何使用容器安全性保护 url 资源,这是我缺少的部分。

标签: java spring tomcat spring-boot


【解决方案1】:

来自official Spring doc

WEB-INF/web.xml 和 WebApplicationInitializer 的使用不是互斥的;例如,web.xml 可以注册一个 servlet,而 WebApplicationInitializer 可以注册另一个。初始化程序甚至可以通过 ServletContext.getServletRegistration(String) 等方法修改在 web.xml 中执行的注册。但是,如果应用程序中存在 WEB-INF/web.xml,则其版本属性必须设置为“3.0”或更高版本,否则 ServletContainerInitializer 引导将被 servlet 容器忽略。

所以,我解决了 WebApplicationInitializer (SpringBootServletInitializer extends WebApplicationInitializer) 和 web.xml

Spring Boot Java 配置类:

 @SpringBootApplication
 public class MyApplication extends SpringBootServletInitializer {

     @Override
     protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
         return application.sources(MyApplication.class);
     }

     public static void main(String[] args) {
         SpringApplication.run(MyApplication.class, args);
     }

      //...
 }

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
metadata-complete="false" version="3.0">

    <display-name>My Awesome Application</display-name>

    <security-constraint>
        <web-resource-collection>
            <web-resource-name>My Awesome Resource Name</web-resource-name>
            <url-pattern>/*</url-pattern>
            <http-method>GET</http-method>
            <http-method>POST</http-method>
            <http-method>PUT</http-method>
            <http-method>DELETE</http-method>
        </web-resource-collection>
        <auth-constraint>
            <role-name>myawesomerole</role-name>
        </auth-constraint>
    </security-constraint>

    <login-config>
        <auth-method>BASIC</auth-method>
    </login-config>

</web-app>

另见:Using Tomcat Basic Auth with new WebApplicationInitializer

【讨论】:

    猜你喜欢
    • 2017-11-10
    • 1970-01-01
    • 2020-01-03
    • 1970-01-01
    • 2018-02-15
    • 1970-01-01
    • 2021-11-26
    • 2018-09-11
    • 2021-07-14
    相关资源
    最近更新 更多