为同一个 REST Api 组合基本身份验证和表单登录 [英] Combining basic authentication and form login for the same REST Api

查看:12
本文介绍了为同一个 REST Api 组合基本身份验证和表单登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法为同一个 REST 服务设置基本身份验证和表单登录?我想让登录用户在登录后通过网络浏览器和从命令行运行 curl -u username:password hostname.com/api/process 触发此服务现在我看到了这篇文章:Basic and form based authentication withSpring 安全 Javaconfig但这与我正在尝试做的略有不同.有没有办法用spring设置它?我现在拥有的是:

Is there a way to set up basic authentication and form login for the same REST service? I'd like to let logged in user trigger this service both through web browser after loggin in and from command line running curl -u username:password hostname.com/api/process Now I've seen this post: Basic and form based authentication with Spring security Javaconfig but it's slightly different from what I'm trying to do. Is there a way to set this up with spring? What I have now is this:

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/indexhostname.com/ 被调用时,它不会重定向到我的登录页面,而是弹出窗口要求基本身份验证凭据.

The only problem is that it doesn't redirect to my login page when hostname.com/index or hostname.com/ is called instead window pop ups asking for basic authentication credentials.

推荐答案

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

You can achieve this easily by using multiple http configuration as below, this code only explains multiple http configuration. I am assuming that you are well aware of the other essential configurations related to spring security e.g authenticationManger etc.

    @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 security官方链接:多重HttpSecurity

Please refer spring security official link: Multiple HttpSecurity

我也会推荐您查看 使用 Spring Security 保护 REST 服务

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

Feel free to comment if you encounter any problem!

这篇关于为同一个 REST Api 组合基本身份验证和表单登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆