Spring 为同一RESTAPI组合基本身份验证和表单登录

Spring 为同一RESTAPI组合基本身份验证和表单登录,spring,authentication,spring-security,Spring,Authentication,Spring Security,有没有办法为同一REST服务设置基本身份验证和表单登录?我想让登录用户在登录后通过web浏览器触发此服务,也可以从运行curl-u username:password hostname.com/api/process的命令行触发此服务 现在我看到了这篇帖子: 但这和我想做的略有不同。 有没有办法用spring来设置? 我现在得到的是: package com.my.company.my.app.security; import org.slf4j.LoggerFactory; import o

有没有办法为同一REST服务设置基本身份验证和表单登录?我想让登录用户在登录后通过web浏览器触发此服务,也可以从运行
curl-u username:password hostname.com/api/process的命令行触发此服务
现在我看到了这篇帖子:
但这和我想做的略有不同。
有没有办法用spring来设置?
我现在得到的是:

package com.my.company.my.app.security;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.JdbcUserDetailsManager;

import javax.sql.DataSource;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(SecurityConfig.class);

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/js/**", "/css/**")
                .permitAll();

        http
                .authorizeRequests()
                .antMatchers("/api/**")
                .authenticated()
                .and()
                .httpBasic();

        http
                .authorizeRequests()
                .antMatchers("/","/index")
                .authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/j_spring_security_check")
                .defaultSuccessUrl("/monitor")
                .failureUrl("/login?error")
                .usernameParameter("j_username")
                .passwordParameter("j_password")
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/j_spring_security_logout")
                .logoutSuccessUrl("/login?logout")
                .permitAll()
                .and()
                .csrf()
                .disable();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
                .passwordEncoder(passwordEncoder())
                .usersByUsernameQuery("SELECT username, password, enabled FROM users WHERE username=?")
                .authoritiesByUsernameQuery("SELECT username, authority FROM authorities WHERE username=?");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder;
    }
}

唯一的问题是,当调用
hostname.com/index
hostname.com/
时,它不会重定向到我的登录页面,而不是请求基本身份验证凭据的窗口弹出窗口

您可以通过使用多个
http
配置轻松实现这一点,如下所示,此代码仅解释多个http配置。我假设您非常了解与spring security相关的其他基本配置,例如AuthenticationManager等

    @EnableWebSecurity
    public class MultiHttpSecurityCustomConfig {
        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication().withUser("user").password("password").roles("USER").and().withUser("admin").password("password")
                    .roles("USER", "ADMIN");
        }

        @Configuration
        @Order(1)
        public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
            protected void configure(HttpSecurity http) throws Exception {
                http.antMatcher("/api/**").authorizeRequests().anyRequest().hasRole("ADMIN").and().httpBasic();
            }
        }

        @Configuration
        public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

            @Override
            protected void configure(HttpSecurity http) throws Exception {
                http.authorizeRequests().anyRequest().authenticated().and().formLogin();
            }


   }
}
请参考spring安全官方链接:

我也会建议你退房


如果您遇到任何问题,请随时发表评论

我发现前面的代码片段在Spring Security 5中不起作用,因为基本身份验证筛选器链中的CSRF筛选器存在问题。可以通过禁用基本身份验证的CSRF使其工作

顺便说一句,表单auth对基本auth的重写是因为重定向到/error页是由此CSRF筛选器问题引起的

@配置
@订单(1)
公共静态类ApiWebSecurity配置适配器扩展了WebSecurity配置适配器{
受保护的无效配置(HttpSecurity http)引发异常{
http.antMatcher(“/api/**”)
.授权请求()
.anyRequest()
.hasRole(“管理员”)
.及()
.httpBasic()
.csrf().disable();
}
}

感谢您接受答案。如果你不介意的话,你可以投我一票!当然可以谢谢你的帮助。我问了一个与这篇文章相关的问题,所以请你帮我解决这个问题@SyntaXThis不再适用于SpringSecurity5.0.8。任何对/api/**的请求都将被重定向到表单登录。请随意添加更改@abedurftigt此链接也会有所帮助:带有Spring安全链接的安全REST服务已失效。