我想要一个基本的受身份验证保护的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);
}
}
控制器
@RestController
public class UserController {
@RequestMapping(value = "/test")
public ResponseEntity test(@AuthenticationPrincipal User user) {
return ResponseEntity.ok().body(user);
}
}
您收到状态码为401的响应。这是“未经授权”的http状态码。这可能是由于您的请求中的Authorization标头缺失/格式不正确造成的。
您正在使用Http-Basic:它在请求中需要以下标头:
Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l
其中字符串QWxhZGRpbjpPcGVuU2VzYW11是<user>:<password>
编码为base64的字符串。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句