Spring Security的基本身份验证(Basic Authentication)是一种HTTP协议定义的简单认证机制,客户端在请求头中发送Base64编码的用户名和密码,格式为Authorization: Basic base64(username:password)
。
当出现未经授权(401 Unauthorized)错误时,通常有以下几种原因:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic()
.authenticationEntryPoint(customBasicAuthenticationEntryPoint())
.and()
.exceptionHandling()
.accessDeniedHandler(customAccessDeniedHandler());
}
@Bean
public AuthenticationEntryPoint customBasicAuthenticationEntryPoint() {
return (request, response, authException) -> {
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().write(
"{\"error\": \"Unauthorized\", \"message\": \"" +
authException.getMessage() + "\"}"
);
};
}
@Bean
public AccessDeniedHandler customAccessDeniedHandler() {
return (request, response, accessDeniedException) -> {
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.getWriter().write(
"{\"error\": \"Forbidden\", \"message\": \"" +
accessDeniedException.getMessage() + "\"}"
);
};
}
}
@ControllerAdvice
public class SecurityExceptionHandler {
@ExceptionHandler(AuthenticationException.class)
public ResponseEntity<ErrorResponse> handleAuthenticationException(AuthenticationException ex) {
ErrorResponse error = new ErrorResponse(
"AUTHENTICATION_FAILED",
ex.getMessage(),
System.currentTimeMillis()
);
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(error);
}
@ExceptionHandler(AccessDeniedException.class)
public ResponseEntity<ErrorResponse> handleAccessDeniedException(AccessDeniedException ex) {
ErrorResponse error = new ErrorResponse(
"ACCESS_DENIED",
ex.getMessage(),
System.currentTimeMillis()
);
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(error);
}
// 错误响应类
@Data
@AllArgsConstructor
private static class ErrorResponse {
private String code;
private String message;
private long timestamp;
}
}
logging.level.org.springframework.security=DEBUG
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
}
@Bean
public UserDetailsService userDetailsService() {
return username -> {
// 实现加载用户逻辑
UserDetails user = userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("User not found"));
if (!user.isEnabled()) {
throw new DisabledException("User account is disabled");
}
return user;
};
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Authorization
头通过以上配置和调试方法,可以有效地处理和调试Spring Security中的基本身份验证未经授权错误。
没有搜到相关的文章