【发布时间】:2019-10-30 07:45:40
【问题描述】:
我正在尝试在通过业务逻辑给出响应之前实现 URL 身份验证。为此,我正在使用 Spring Security 的身份验证提供程序,并尝试做一个简单的演示来测试 authenticationProvider 是否正常工作。在此之后,我将通过添加我的业务逻辑进行修改。
我的安全配置文件 SecurityConfig.java 如下,
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAuthenticationProvider authenticationProvider;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests()
.anyRequest()
.authenticated()
.and().httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception
{
auth.authenticationProvider(authenticationProvider);
}
}
我的 CustomAuthenticationProvider.java 实现如下,
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider
{
@SuppressWarnings("unused")
@Override
public Authentication authenticate(Authentication authToken) throws AuthenticationException {
String userToken = (String) authToken.getName();
String responseString = "test";
String password = "test";
if(responseString.equals(userToken)) {
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(userToken, password);
return auth;
}
else {
return null;
}
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
我的 TestSecurity.java 如下所示,
@RestController
public class TestSecurity {
@GetMapping("/security/load")
public String LoadSecureUsers() {
return "hello spring security";
}
}
当我从 POSTMAN 应用程序调用带有标头 authToken: "test" 的 URL localhost:8585/security/load 时,我得到以下信息,
{
"timestamp": "2019-10-30T07:24:25.165+0000",
"status": 401,
"error": "Unauthorized",
"message": "Unauthorized",
"path": "/security/load"
}
如果IF中的条件满足,那么URL怎么不能访问呢?我在身份验证提供程序实现中犯了任何错误吗?
【问题讨论】:
-
您启用了基本身份验证,因此您应该发送正确的身份验证标头。您在自定义身份验证提供程序中执行某些操作这一事实不会阻止基本身份验证工作。 (这反过来会调用您的身份验证提供程序)。除此之外,它仍然会失败,因为您没有为用户分配任何权限,经过身份验证的标志将在
UsernamePasswordAuthenticationToken中保持false。为什么要打扰您的自定义提供商?只需使用内存数据库并在其中配置一个用户。
标签: spring-boot spring-security