我有一个启用了Spring Security的基本Spring Boot API。当从Vue内部访问安全资源时(使用axios),浏览器将向我请求用户名和密码,并显示“需要授权”弹出窗口。之后,凭据似乎由浏览器存储,我可以继续发出请求。
我应该如何绕过浏览器进行的身份验证过程,并将其替换为由Vue Js直接制作和控制的过程?
答案 0 :(得分:5)
@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"));
}
}
}
Authorization: Basic qwerasdfzxcv
qwerasdfzxcv
是由username:password