我可以从BasicAuth实施Header授权吗?

时间:2018-06-03 14:13:15

标签: spring spring-boot spring-security

我是Spring的新手,我使用this tutorial实现了BasicAuth。有没有办法可以无痛地实现授权头而不是BasicAuth?配置SecurityConfig足够了吗?我正在构建一个Web服务。 如果它有帮助,这是我的SecurityConfig

package com.example.infobip.config;

import com.example.infobip.IUrlService;
import com.example.infobip.repositories.UsersRepository;
import com.example.infobip.service.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
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.password.PasswordEncoder;

@EnableWebSecurity
@EnableJpaRepositories(basePackageClasses = UsersRepository.class)
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService userDetailsService;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(new PasswordEncoder() {
            @Override
            public String encode(CharSequence charSequence) {
                return charSequence.toString();
            }

            @Override
            public boolean matches(CharSequence charSequence, String s) {
                return true;
            }
        });
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
                http.authorizeRequests()
                .antMatchers("/statistic/**", "/register").authenticated()
                .anyRequest().permitAll()
                .and()
                .formLogin()
                .permitAll()
                .and()
                .logout()
                .permitAll();
    }
}

1 个答案:

答案 0 :(得分:0)

我终于成功了!我应该在http.csrf()。disable()之后添加.httpBasicAuth()。此外,this tutorial有很多帮助。