首页 > 解决方案 > 使用带有 Angular 6 的 Spring Security 进行 Http 基本身份验证

问题描述

我正在开发一个 Angular 6 应用程序,我将 Spring Boot 用于 REST 服务并使用 Spring security Basic 身份验证进行授权。

问题是,基本身份验证不起作用,每次我登录应用程序时都会弹出。我在 Angular 6 中使用拦截器来添加授权标头。

任何人都可以帮助我去哪里错了吗?

代码 :

@Injectable()
export class HttpTokenInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<any> | HttpUserEvent<any>> {
        let username=localStorage.getItem("username")
        let password=localStorage.getItem("password")
        const customReq = req.clone({
            headers: req.headers.set("Authorization", "Basic " + btoa(username+":"+password) )
        });
        return next.handle(customReq);
    }

    constructor() { }
}

和弹簧启动代码

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.httpBasic().and().authorizeRequests().antMatchers("/index.html", "/", "/home/**", "/login").permitAll()
                .anyRequest().authenticated().and().csrf().disable().httpBasic();

    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userDetailsService);
        authProvider.setPasswordEncoder(encoder());
        return authProvider;
    }

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

由于我是 Spring 新手,如果您需要任何其他文件,请告诉我。

标签: spring-bootspring-securityangular6angular-http-interceptors

解决方案


这通常发生在您@SpringBootApplication类在一个包中并且您的SecurityConfig类不存在于子包中时。

例如,如果应用程序在com.example.app包中并且您的安全配置在其中,com.security.example那么 Spring 找不到您的配置并继续使用 Spring 安全默认值,例如基于表单的登录页面。

如果需要,请检查包结构并添加@ComponentScan


推荐阅读