gpt4 book ai didi

spring - 未调用自定义 AuthenticationProvider

转载 作者:行者123 更新时间:2023-12-01 02:00:59 27 4
gpt4 key购买 nike

我想要一个基本的受身份验证保护的 REST 应用程序。我遵循了 http://www.baeldung.com/spring-security-authentication-provider 中的一般说明为了让安全工作。

我最终创建了 AuthenticationProvider 的实现,但它永远不会被 Spring 调用。所有请求都以错误结束:

{"timestamp":1460199213227,"status":401,"error":"Unauthorized","message":"Full authentication is required to access this resource","path":"/test"}

没有 AuthenticationProvider 做任何事情。

该应用程序是基于注释的,以下是相关部分:

安全设置
@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class ApplicationSecurity extends WebSecurityConfigurerAdapter {
@Autowired
CustomAuthenticationProvider authenticationProvider;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider);
}

@Override
public void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authenticationProvider(authenticationProvider)
.authorizeRequests()
.anyRequest().authenticated().and().httpBasic();
}
}

身份验证提供者
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Autowired
private UserDAO userDAO;
@Autowired
private Authenticator authenticator;

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
// This never gets called, I checked with debugger
String username = authentication.getName();
String password = authentication.getCredentials().toString();

User user = userDAO.findByUsername(username);
User authenticatedUser = authenticator.authenticate(user, password);
if (authenticatedUser == null){
throw new RESTAuthenticationException("Auth failed");
}

List<GrantedAuthority> authorityList = new ArrayList<>();
return new UsernamePasswordAuthenticationToken(user, authorityList);
}

@Override
public boolean supports(Class<?> aClass) {
return aClass.equals(UsernamePasswordAuthenticationToken.class);
}
}

Controller
@RestController
public class UserController {
@RequestMapping(value = "/test")
public ResponseEntity test(@AuthenticationPrincipal User user) {
return ResponseEntity.ok().body(user);
}
}

最佳答案

您收到状态代码为 401 的响应。这是 "unauthorized" http status code .这可能是由您的请求中缺少/格式错误的 Authorization header 引起的。

您正在使用 Http-Basic :它需要在请求中包含以下 header :

Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l

其中字符串 QWxhZGRpbjpPcGVuU2VzYW1l 是字符串 <user>:<password> base64 编码。

关于spring - 未调用自定义 AuthenticationProvider,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36515895/

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