Vue Js和Spring Boot基本身份验证

时间:2017-04-03 13:28:22

标签: spring-boot vue.js basic-authentication

我有一个启用了Spring Security的基本Spring Boot API。当从Vue内部访问安全资源时(使用axios),浏览器将向我请求用户名和密码,并显示“需要授权”弹出窗口。之后,凭据似乎由浏览器存储,我可以继续发出请求。

我应该如何绕过浏览器进行的身份验证过程,并将其替换为由Vue Js直接制作和控制的过程?

1 个答案:

答案 0 :(得分:5)

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

@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哈希