Java 当我向同时是';管理员';和';用户';
我一直从邮递员那里得到的只是这个错误,我不知道如何修复它: 我提出的GET请求是:Java 当我向同时是';管理员';和';用户';,java,spring,hibernate,spring-boot,jwt,Java,Spring,Hibernate,Spring Boot,Jwt,我一直从邮递员那里得到的只是这个错误,我不知道如何修复它: 我提出的GET请求是: localhost:8080/api/v1/user/5?Authorization=Bearer-eyJhbGciOiJIUzUxMiJ9.eyjzdwiiiximocisimlhdci6mtu4otgwndkxnywizxhwijoxntkwmjm2ote3fq.s0hcsw8kszup6ruqdutt8tox3b-eUsGO4YW-kvolyez4bdgitxqkg143xft-vAGUvrvquEjIQ[
localhost:8080/api/v1/user/5?Authorization=Bearer-eyJhbGciOiJIUzUxMiJ9.eyjzdwiiiximocisimlhdci6mtu4otgwndkxnywizxhwijoxntkwmjm2ote3fq.s0hcsw8kszup6ruqdutt8tox3b-eUsGO4YW-kvolyez4bdgitxqkg143xft-vAGUvrvquEjIQ[![在此处输入图像描述][1]
输出为:
{
"timestamp": "2020-05-18T12:39:38.405+0000",
"status": 401,
"error": "Unauthorized",
"message": "You're not authorized to access this resource.",
"path": "/api/v1/user/5"
}
这是我在WebConfig类中的配置:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/v1/auth/signin", "/api/v1/auth/register")
.permitAll()
.antMatchers(HttpMethod.GET, "/api/v1/user")
.permitAll()
.anyRequest()
.authenticated();
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
这是我的控制器。这些方法运行良好,但我将其作为参考发布:
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/v1/auth")
public class AuthController {
RoleServiceImpl roleService;
UserServiceImpl userService;
PasswordEncoder passwordEncoder;
AuthenticationManager authenticationManager;
JwtUtils jwtUtils;
@Autowired
public AuthController(RoleServiceImpl roleService, UserServiceImpl userService,
PasswordEncoder passwordEncoder, AuthenticationManager authenticationManager,
JwtUtils jwtUtils) {
this.roleService = roleService;
this.userService = userService;
this.passwordEncoder = passwordEncoder;
this.authenticationManager = authenticationManager;
this.jwtUtils = jwtUtils;
}
@PostMapping("/signin")
public HttpEntity authenticate(@Valid @RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken
(loginRequest.getEmail(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
List<String> roles = userDetails.getAuthorities().stream()
.map(item -> item.getAuthority())
.collect(Collectors.toList());
JwtResponse jwtResponse = new JwtResponse(jwt,
userDetails.getId(),
userDetails.getEmail(),
roles);
return ResponseEntity.ok(jwtResponse);
}
@PostMapping("/register")
public HttpEntity authenticate(@Valid @RequestBody RegisterRequest registerRequest) {
if (userService.existsByEmail(registerRequest.getEmail())) {
throw new BadRequestException("Email already exists");
}
User user = UserMapper.INSTANCE.registerRequestoUser(registerRequest);
user.setPassword(passwordEncoder.encode(user.getPassword()));
Set<String> strRoles = registerRequest.getRoles();
Set<Role> roles = new HashSet<>();
if (strRoles == null) {
Role userRole = roleService.getByName("user")
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(userRole);
} else {
for (String role : strRoles) {
if (role.equals("administrator")) {
Role adminRole = roleService.getByName("administrator")
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(adminRole);
}
if (role.equals("user")) {
Role userRole = roleService.getByName("user")
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(userRole);
break;
}
}
}
user.setRoles(roles);
userService.create(user);
return ResponseEntity.ok("Success");
}
}
@CrossOrigin(origins=“*”,maxAge=3600)
@RestController
@请求映射(“/api/v1/auth”)
公共类授权控制器{
角色服务impl角色服务;
UserServiceImpl用户服务;
密码编码器;
AuthenticationManager AuthenticationManager;
JwtUtils JwtUtils;
@自动连线
公共授权控制器(RoleServiceImpl roleService、UserServiceImpl userService、,
PasswordEncoder PasswordEncoder,AuthenticationManager AuthenticationManager,
JwtUtils(JwtUtils){
this.roleService=roleService;
this.userService=userService;
this.passwordEncoder=passwordEncoder;
this.authenticationManager=authenticationManager;
this.jwtUtils=jwtUtils;
}
@邮戳(“/签名”)
公共HttpEntity身份验证(@Valid@RequestBody LoginRequest LoginRequest){
Authentication=authenticationManager.authenticate(
新用户名PasswordAuthenticationToken
(loginRequest.getEmail(),loginRequest.getPassword());
SecurityContextHolder.getContext().setAuthentication(身份验证);
字符串jwt=jwtUtils.generateJwtToken(身份验证);
UserDetailsImpl userDetails=(UserDetailsImpl)身份验证。getPrincipal();
List roles=userDetails.getAuthorities().stream()
.map(项目->项目.getAuthority())
.collect(Collectors.toList());
JwtResponse JwtResponse=新JwtResponse(jwt,
userDetails.getId(),
userDetails.getEmail(),
角色);
返回ResponseEntity.ok(jwtResponse);
}
@后映射(“/寄存器”)
公共HttpEntity身份验证(@Valid@RequestBody RegisterRequest RegisterRequest){
if(userService.existsByEmail(registerRequest.getEmail()){
抛出新的BadRequestException(“电子邮件已存在”);
}
User User=UserMapper.INSTANCE.RegisterRequestUser(registerRequest);
user.setPassword(passwordEncoder.encode(user.getPassword());
Set stroles=registerRequest.getRoles();
Set roles=new HashSet();
如果(strRoles==null){
Role userRole=roleService.getByName(“用户”)
.orelsetrow(()->new RuntimeException(“错误:找不到角色”);
roles.add(userRole);
}否则{
for(字符串角色:strRoles){
if(角色等于(“管理员”)){
Role adminRole=roleService.getByName(“管理员”)
.orelsetrow(()->new RuntimeException(“错误:找不到角色”);
角色.添加(管理员);
}
if(role.equals(“用户”)){
Role userRole=roleService.getByName(“用户”)
.orelsetrow(()->new RuntimeException(“错误:找不到角色”);
roles.add(userRole);
打破
}
}
}
user.setRoles(角色);
创建(用户);
返回响应。ok(“成功”);
}
}
我开始有问题了。当我访问其中一些方法时,甚至当我提供令牌时,仍然会出现未经授权的错误
@RequestMapping("/api/v1/user")
@RestController
public class UserController {
private final UserServiceImpl userService;
private PasswordEncoder passwordEncoder;
@Autowired
public UserController(UserServiceImpl userService, PasswordEncoder passwordEncoder) {
this.userService = userService;
this.passwordEncoder=passwordEncoder;
}
@GetMapping(value = "/{id}")
public HttpEntity get(@PathVariable(name = "id") Long id) {
Optional<User> userOptional = userService.get(id);
if (userOptional.isPresent()) {
return ResponseEntity.ok(UserMapper.INSTANCE.userToUserGetDTO(userOptional.get()));
}
throw new RecordNotFoundException("Invalid user id : " + id);
}
@GetMapping
public HttpEntity get() {
List<User> users = userService.get();
List<UserGetDTO> userGetDTOS = new ArrayList<>();
if (users.isEmpty()) {
throw new RecordNotFoundException("No users");
}
for (User user : users) {
userGetDTOS.add(UserMapper.INSTANCE.userToUserGetDTO(user));
}
return ResponseEntity.ok(userGetDTOS);
}
@PostMapping
public HttpEntity create(@Valid @RequestBody UserPostDTO userPostDTO) {
User user = UserMapper.INSTANCE.userPostDTOtoUser(userPostDTO);
user.setPassword(passwordEncoder.encode(user.getPassword()));
Optional<User> userOptional = userService.create(user);
if (userOptional.isPresent()) {
return ResponseEntity.ok(UserMapper.INSTANCE.userToUserGetDTO(user));
}
throw new BadRequestException("Unprocessable entity");
}
@请求映射(“/api/v1/user”)
@RestController
公共类用户控制器{
私有最终用户服务impl用户服务;
专用密码编码器;
@自动连线
公共用户控制器(UserServiceImpl userService、PasswordEncoder PasswordEncoder){
this.userService=userService;
this.passwordEncoder=passwordEncoder;
}
@GetMapping(value=“/{id}”)
公共HttpEntity get(@PathVariable(name=“id”)长id){
Optional userOptional=userService.get(id);
if(userOptional.isPresent()){
返回ResponseEntity.ok(UserMapper.INSTANCE.usertoUserToUserGetDTO(userOptional.get());
}
抛出新的RecordNotFoundException(“无效用户id:+id”);
}
@GetMapping
公共HttpEntity get(){
List users=userService.get();
List userGetDTOS=new ArrayList();
if(users.isEmpty()){
抛出新的RecordNotFoundException(“无用户”);
}
for(用户:用户){
添加(UserMapper.INSTANCE.userToUserGetDTO(用户));
}
返回ResponseEntity.ok(userGetDTOS);
}
@邮戳
公共HttpEntity创建(@Valid@RequestBody UserPostDTO UserPostDTO){
User User=UserMapper.INSTANCE.userpostdtouser(userPostDTO);
user.setPassword(passwordEncoder.encode(user.getPassword());
Optional userOptional=userService.create(用户);
if(userOptional.isPresent()){
返回ResponseEntity.ok(UserMapper.INSTANCE.UserToUserToUserGetDTO(用户));
}
抛出新的BadRequestException(“不可处理实体”);
}
如果可以调试代码并将请求委托给spring security类,则可以看到validate(实际的,提供的)方法失败
这主要是因为Bcrypt编码器哈希不匹配,它应该以$2a或$2x开头
我建议使用BCryptPasswordEncoder
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String encodedPassword = passwordEncoder.encode(password);