【发布时间】:2022-01-21 15:19:43
【问题描述】:
我添加了spring安全依赖,之后我启动了服务器,一切顺利。结果我得到了一个带有用户名和密码的表单,我输入 user 作为用户名和密码作为我在控制台中得到的那个,
Using generated security password: 8c3450f7-ab6c-419e-bd69-431ed336eeaa
但我总是得到用户名或密码不正确。
班级Security:
package security;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter{
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and()
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/users")
.permitAll()
.anyRequest().authenticated();
}
}
这是我尝试访问的链接http://localhost:8081/users
对我正在犯的错误有什么想法吗?
班级UserController:
RestController
@RequestMapping("/users") // localhosr:8080/users
public class userController {
@Autowired
UserService userService;
@GetMapping
public String getUser() {
return " get user was called ";
}
@PostMapping
public UserResponse createUser(@RequestBody UserRequest userRequest) {
UserDto userDto = new UserDto();
BeanUtils.copyProperties(userRequest, userDto);
UserDto createUser = userService.createUser(userDto);
UserResponse userResponse = new UserResponse();
BeanUtils.copyProperties(createUser, userResponse);
return userResponse ;
}
@PutMapping
public String updateUser() {
return " update user was called ";
}
@DeleteMapping
public String deleteUser() {
return " delete user was called ";
}
}
在失眠中,对于 Get 方法,我收到错误 401 Unauthorized
PS:我已经删除了 WebSecurity 类,我正在尝试访问 localhost:8081/users,我总是得到一个登录表单并且无法登录。
【问题讨论】:
-
.antMatchers(HttpMethod.POST, "/users")只允许 POST 请求。您可能想使用类似antMatchers("/users")的东西,它允许任何类型的请求。请注意,这将使/users端点公开。 -
但我只想允许创建用户的 Post 请求,其他任何东西都需要登录,我尝试了 antMatchers("/users"),但它总是显示登录表单
-
@dEs12ZER 您发布问题的方式很难理解和阅读。请花点时间查看对您的帖子所做的修改,以了解未来需要注意的事项。您不应该依赖他人来使您的帖子清晰可见
标签: java spring spring-boot spring-security