gpt4 book ai didi

java - Spring 返回 401 而不是 200 状态

转载 作者:搜寻专家 更新时间:2023-10-31 20:16:51 28 4
gpt4 key购买 nike

作为学习 Spring 的一部分,我编写了一个应用程序,但是当我测试身份验证时,我收到 401 状态而不是 200。我正在寻找错误的原因,在我看来 Authentication authentication = authenticationManager .authenticate(new UsernamePasswordAuthenticationToken(email, password)); 返回 null。但是,我不知道如何解决这个问题。

@Component
public class AuthenticationServiceUsernamePassword {
private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationServiceUsernamePassword.class);
@Autowired
@Qualifier("customAuthenticationManager")
private AuthenticationManager authenticationManager;
@Autowired
private TokenManager tokenManager;

public SignedJWT authenticate(final String email, final String password){
try {
Authentication authentication = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken(email, password));
SecurityContextHolder.getContext()
.setAuthentication(authentication);

if (authentication.getPrincipal() != null) {
return tokenManager.createNewToken((PrincipalUser) authentication.getPrincipal());
}
} catch (AuthenticationException authException) {
LOGGER.debug("Authentication failed for user:\"" + email + ".\" Reason " + authException.getClass());
}

return null;
}
}

Controller

@Controller
public class AuthController {
@Value("${jwt.result}")
private String defaultTokenResponse;
@Autowired
private AuthenticationServiceUsernamePassword authUserPassword;

@RequestMapping(value = "/authentication", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> authenticate(String email, String password, HttpServletRequest request,
HttpServletResponse response){
if (email != null && password != null){
try {
SignedJWT token = authUserPassword.authenticate(email, password);

if (token != null){
return new ResponseEntity<String>(String.format(defaultTokenResponse, token.serialize()),
HttpStatus.OK);
} else {
return new ResponseEntity<String>(HttpStatus.UNAUTHORIZED);
}
} catch (BadCredentialsException badCredentials) {
return new ResponseEntity<String>(HttpStatus.UNAUTHORIZED);
}
} else {
return new ResponseEntity<String>(HttpStatus.UNAUTHORIZED);
}
}
}

测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
@WebAppConfiguration
public class ConnectControllerTest {
protected MockMvc mockMvc;
@Autowired
private WebApplicationContext context;
@Autowired
private Filter springSecurityFilterChain;

@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(context)
.addFilters(springSecurityFilterChain)
.defaultRequest(get("/"))
.build();
}

@Test
public void shouldTestAuthentication() throws Exception {
String result = mockMvc.perform(post("/authentication")
.param("email", "user@test.pl").param("password", "password"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.token").exists())
.andReturn().getResponse().getContentAsString();
}
}

如果有人对这里的其余代码感兴趣,请访问链接:repository

最佳答案

好的。有事先做

EmailPassword 正确传递

问题来了

public SignedJWT authenticate(final String email, final String password){
try {
System.out.println("test => "+email+" : "+password);
Authentication authentication = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken(email, password));
SecurityContextHolder.getContext().setAuthentication(authentication);

if (authentication.getPrincipal() != null) {
return tokenManager.createNewToken((PrincipalUser) authentication.getPrincipal());
}
} catch (AuthenticationException authException) {
authException.printStackTrace();
LOGGER.debug("Authentication failed for user:\"" + email + ".\" Reason " + authException.getClass());
}
System.out.println("return nulll");
return null;
}

如果你运行你的测试用例,它会抛出以下错误

org.springframework.security.authentication.BadCredentialsException: Bad credentials
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.additionalAuthenticationChecks(DaoAuthenticationProvider.java:98)
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:166)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:199)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$AuthenticationManagerDelegator.authenticate(WebSecurityConfigurerAdapter.java:504)
at com.github.springjwt.security.jwt.service.AuthenticationServiceUsernamePassword.authenticate(AuthenticationServiceUsernamePassword.java:30)
at com.github.springjwt.web.api.controller.AuthController.authenticate(AuthController.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImp

这意味着您的测试用例的usernamepasswordUserRepository 类用户详细信息不匹配

在您的 UserRepository 类中 您需要设置正确的散列密码及其已设置为空的盐值。

当您调用 authenticate.authenticate 时,它会在内部获取密码和哈希并将其与传递的值进行匹配。

如果值不匹配,它会抛出 Bad credentials 错误

P.S:我在本地运行你的代码后得出了这个结论

关于java - Spring 返回 401 而不是 200 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52870953/

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