【问题标题】:Vue Js and Spring Boot Basic AuthenticationVue Js 和 Spring Boot 基本认证
【发布时间】:2017-05-27 09:38:11
【问题描述】:

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

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

【问题讨论】:

  • 如果你真的想保留基本身份验证,你需要在你的请求中发送一个身份验证标头。您可以在 axios 中定义拦截器,以确保它们随每个请求一起发送。但是我更喜欢使用 cookie / jwt 令牌进行身份验证。
  • 我假设我必须配置 Spring Boot 来处理 JWT?知道这方面的任何参考吗?
  • 我认为这很好地解释了它:svlada.com/jwt-token-authentication-with-spring-boot - 但是 - 如果您是 auth 和 vue 的新手,我建议您在第一次尝试时尝试在每个请求中发送 Basic Auth Header进入主题。您不需要大量的代码,这是一个很好的培训。

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


【解决方案1】:

首先,添加安全配置(假设你使用的是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 哈希

【讨论】:

    猜你喜欢
    • 2018-02-14
    • 2020-11-14
    • 2019-02-02
    • 2018-10-07
    • 2018-09-07
    • 2018-09-04
    • 2016-10-22
    • 1970-01-01
    相关资源
    最近更新 更多