【发布时间】:2022-01-13 17:20:50
【问题描述】:
我是初学者。我将 Spring Boot 应用程序用于 REST API。我需要前端(Angular 应用程序)联系 Springapp 以登录并访问数据库。问题出在我身上,我不知道如何让 Spring 安全通过 JSON RequestBody 登录???我想要使用 JSON 进行授权
控制器内容
@PostMapping (value = "/login-koko")
public String authPost(@RequestBody AuthDTO user) {
System.out.println(user.getPassword());
return "SuccessPost";
}
@GetMapping (value = "/login-koko")
public String authGet() {
return "SuccessGet";
}
这实现了 WebMvcConfigurer
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login-koko");
}
这扩展了 WebSecurityConfigurerAdapter
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated()
.and()
.addFilterAt(new CustomUsernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.formLogin()
.loginPage("/login-koko").permitAll()
.loginProcessingUrl("/login-koko").permitAll()
.and()
.logout().permitAll()
.and()
.rememberMe()
.and()
.cors().disable()
.csrf().disable();
}
这是我的过滤器 CustomUsernamePasswordAuthenticationFilter
@Override
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
try {
BufferedReader reader = request.getReader();
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
String parsedReq = sb.toString();
if (parsedReq != null) {
ObjectMapper mapper = new ObjectMapper();
AuthDTO authDTO = mapper.readValue(parsedReq, AuthDTO.class);
return new UsernamePasswordAuthenticationToken(authDTO.getUsername(), authDTO.getPassword());
}
} catch (Exception e) {
System.out.println(e.getMessage());
throw new InternalAuthenticationServiceException("Failed to parse authentication request body");
}
return null;
}
我的登录和通过
spring.security.user.name=qwesan
spring.security.user.password=qwesan
邮递员 但没有授权[https://sun9-71.userapi.com/impg/BpfC5xCcjIyOdkz-XSN--3pHJ-3PcoLzcx_msw/WITWaWxKuhw.jpg?size=1193x509&quality=96&sign=b80141825c9ee8d54d62a7b9419d7d45&type=album]
为什么没用
【问题讨论】:
-
请澄清您的具体问题或提供更多详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。
标签: java spring spring-boot spring-security