Java Spring Security HTTP Basic for RESTFul 和 FormLogin (Cookies) for web - 注释

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27774742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 05:00:28  来源:igfitidea点击:

Spring Security HTTP Basic for RESTFul and FormLogin (Cookies) for web - Annotations

javaspringspring-mvcspring-securityspring-boot

提问by Faraj Farook

In Specific

在特定

I want to have HTTP Basic authentication ONLY for a specific URL pattern.

我只想对特定的 URL 模式进行 HTTP 基本身份验证。

In Detail

详细

I'm creating an API interface for my application and that needs to be authenticated by simple HTTP basic authentication. But other web pages should notbe using HTTP basic but rather a the normal form login.

我正在为我的应用程序创建一个 API 接口,需要通过简单的HTTP 基本身份验证进行身份验证。但是其他网页应该使用 HTTP basic 而是使用正常的表单登录。

Current Configuration - NOT Working

当前配置 - 不工作

@Override
protected void configure(HttpSecurity http) throws Exception {
    http //HTTP Security
            .csrf().disable() //Disable CSRF
            .authorizeRequests() //Authorize Request Configuration
                .antMatchers("/connect/**").permitAll()
                .antMatchers("/", "/register").permitAll()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/api/**").hasRole("API")
                .anyRequest().authenticated()
            .and() //HTTP basic Authentication only for API
                .antMatcher("/api/**").httpBasic()
           .and() //Login Form configuration for all others
                .formLogin().loginPage("/login").permitAll()
            .and() //Logout Form configuration
                .logout().permitAll();

}

采纳答案by Faraj Farook

Waited for 2 days and didn't get any help here. But my research provided me a solution :)

在这里等了 2 天,并没有得到任何帮助。但我的研究为我提供了一个解决方案:)

Solution

解决方案

@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true, proxyTargetClass = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private AuthenticationProvider authenticationProvider;

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

    @Configuration
    @Order(1)
    public static class ApiWebSecurityConfig extends WebSecurityConfigurerAdapter{
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable()
                    .antMatcher("/api/**")
                    .authorizeRequests()
                        .anyRequest().hasAnyRole("ADMIN", "API")
                        .and()
                    .httpBasic();
        }
    }

    @Configuration
    @Order(2)
    public static class FormWebSecurityConfig extends WebSecurityConfigurerAdapter{

        @Override
        public void configure(WebSecurity web) throws Exception {
            web.ignoring().antMatchers("/css/**", "/js/**", "/img/**", "/lib/**");
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable() //HTTP with Disable CSRF
                    .authorizeRequests() //Authorize Request Configuration
                        .antMatchers("/connect/**").permitAll()
                        .antMatchers("/", "/register").permitAll()
                        .antMatchers("/admin/**").hasRole("ADMIN")
                        .anyRequest().authenticated()
                        .and() //Login Form configuration for all others
                    .formLogin()
                        .loginPage("/login").permitAll()
                        .and() //Logout Form configuration
                    .logout().permitAll();
        }
    }
}

回答by Andrea L.

I dunno if it can be helpful but I couldn't implement the above solution. I found a workaround defining a single Security

我不知道它是否有帮助,但我无法实施上述解决方案。我找到了一个定义单个安全性的解决方法

@Configuration class

@配置类

extending

延伸

WebSecurityConfigurerAdapter

网络安全配置器适配器

with both httpBasic() and formLogin() configured. Then I created a custom

配置了 httpBasic() 和 formLogin() 。然后我创建了一个自定义

CustomAuthEntryPoint implements AuthenticationEntryPoint

CustomAuthEntryPoint 实现 AuthenticationEntryPoint

that has this logic in the commence method:

在 begin 方法中有这个逻辑:

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException
   {
        String urlContext = UtilityClass.extractUrlContext(request);
        if (!urlContext.equals(API_URL_PREFIX))
        {
            String redirectUrl = "urlOfFormLogin"
            response.sendRedirect(request.getContextPath() + redirectUrl);
       }
        else
        {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }

Dunno which is the "best practice strategy" about this issue

不知道这是关于这个问题的“最佳实践策略”