java—如何为给定的servlet启用现有的Spring Security ?

irlmq6kh  于 2021-07-13  发布在  Java
关注(0)|答案(0)|浏览(248)

我部署了一个servlet myservlet.java

@Configurable
public class MyServlet extends HttpServlet {

    @Autowired
    MyService service;

    @Override
    public void init(ServletConfig config) throws javax.servlet.ServletException{
        super.init(config);
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) {
    //Do something here
    }

现在,在web.xml中启用了安全性,如下所示:

<security-constraint>
        <web-resource-collection>
            <web-resource-name>myServlet</web-resource-name>
            <url-pattern>/myUrl/*</url-pattern>
            <http-method>HEAD</http-method>
            <http-method>POST</http-method>
        </web-resource-collection>
        <auth-constraint>
            <role-name>user</role-name>
        </auth-constraint>
        <user-data-constraint>
            <transport-guarantee>NONE</transport-guarantee>
        </user-data-constraint>
    </security-constraint>
    <login-config>
        <auth-method>BASIC</auth-method>
    </login-config>
    <security-role>
        <role-name>user</role-name>
    </security-role>

但是部署的这个spring应用程序已经通过 @EnableWebSecurity spring应用程序中部署的控制器都正确地获得了预期的身份验证。但是servlet没有使用Spring Security 进行身份验证。我相信报告中提到的是阻止它进行身份验证。
如何使servlet与Spring Security 一起工作?
编辑1:spring安全配置:(注意这在语法上是不正确的),但是在我的代码中用户/角色和数据源都是正确的。对于spring应用程序中部署的其他restapi来说,它工作得很好

@Configuration
@EnableWebSecurity(debug = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {

        String user_query = "select user from userTable where id=9999";

        String role_query = "select role from roleTable where id=6666";
        logger.info("Using the following query for role : " + role_query);

        auth.
                jdbcAuthentication()
                .dataSource(dataSource) //Datasource is injected to this class
                .usersByUsernameQuery(user_query)
                .passwordEncoder(passwordEncoder())
                .authoritiesByUsernameQuery(role_query);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .anyRequest().hasRole("myrole")
                .and()
                .httpBasic();

    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(runAsAuthenticationProvider());
    }

    @Autowired
    protected RunAsManager runAsManager() {
        RunAsManagerImpl runAsManager = new RunAsManagerImpl();
        runAsManager.setKey("MyRunAsKey");
        return runAsManager;
    }

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题