gpt4 book ai didi

spring-boot - Vue Js 和 Spring Boot 基本身份验证

转载 作者:搜寻专家 更新时间:2023-10-30 22:15:28 24 4
gpt4 key购买 nike

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

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

最佳答案

首先,添加安全配置(假设你使用的是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请求头中添加鉴权,格式如下:

  • 授权:基本 qwerasdfzxcv
  • qwerasdfzxcv 是由username:password
  • 编码的base64 hash

关于spring-boot - Vue Js 和 Spring Boot 基本身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43185933/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com