Vue Js 和 Spring 引导基本身份验证

Vue Js and Spring Boot Basic Authentication

我有一个基本的 Spring 引导 API,启用了 Spring 安全。当从 Vue 中访问受保护的资源时(使用 axios),浏览器将通过 "Authorization Required" 弹出窗口要求我输入用户名和密码。之后,凭据似乎被浏览器存储,我可以继续发出请求。

如何绕过浏览器做的认证过程,换成Vue Js直接做的和控制的?

首先,添加安全配置(假设您使用的是Spring安全):

@Configuration
public class ApiSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
                .antMatchers("/api/**").authenticated()
                .anyRequest().permitAll()
                .and().httpBasic().authenticationEntryPoint(apiAwareLoginUrlAuthenticationEntryPoint())
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

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

    @Bean
    public ApiBasicAuthenticationEntryPoint apiAwareLoginUrlAuthenticationEntryPoint() {
        ApiBasicAuthenticationEntryPoint entryPoint = new ApiBasicAuthenticationEntryPoint();
        entryPoint.setRealmName("Api Server");
        return entryPoint;
    }

    public static class ApiBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {

        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
            response.addHeader("WWW-Authenticate", "Basic realm=\"" + getRealmName() + "\"");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            //response.setContentType("");
            PrintWriter writer = response.getWriter();
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(writer, ApiDataGenerator.buildResult(
                    ErrorCode.AUTHORIZATION_REQUIRED, "Authorization failed"));
        }

    }
}

其次,在http请求头中添加鉴权格式如下:

  • Authorization: Basic qwerasdfzxcv
  • qwerasdfzxcv 是由 username:password
  • 编码的 base64 哈希