03.访问与鉴权

访问与鉴权

首先是用户的注册与登录:


@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/auth")
public class AuthController {

  @Autowired private AuthenticationManager authenticationManager;

  @Autowired private TokenProvider jwtTokenUtil;

  @Autowired private UserService userService;

  @RequestMapping(value = "/sign_in", method = RequestMethod.POST)
  public ResponseEntity<?> sign_in(@RequestBody LoginUser loginUser)
      throws AuthenticationException {

    final Authentication authentication =
        authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(
                loginUser.getUsername(), loginUser.getPassword()));

    SecurityContextHolder.getContext().setAuthentication(authentication);
    final String token = jwtTokenUtil.generateToken(authentication);
    return ResponseEntity.ok(new AuthToken(token));
  }

  @RequestMapping(value = "/sign_up", method = RequestMethod.POST)
  public User saveUser(@RequestBody UserDTO user) {
    return userService.save(user);
  }
}

我们需要使用声明的编码器加密密码后放入数据库:

@Override
public User save(UserDTO user) {
    User newUser = new User();
    newUser.setUsername(user.getUsername());
    newUser.setPassword(bcryptEncoder.encode(user.getPassword()));
    newUser.setAge(user.getAge());
    newUser.setSalary(user.getSalary());
    return userDao.save(newUser);
}

而在登录的时候:

authenticationManager.authenticate(
    new UsernamePasswordAuthenticationToken(
        loginUser.getUsername(), loginUser.getPassword()));

authenticationManager 会根据传入的用户信息,调用 UserDetailsService 判断用户是否真实,然后创建 JWT 的 Token 并返回。注意,这里是把密码从数据库中读取出来,然后再次进行核对。最后在具体的接口访问,譬如在访问用户信息时,我们可以通过注解来指定某个接口的权限控制:

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
public class UserController {

  @Autowired private UserService userService;

  // @Secured({"ROLE_ADMIN", "ROLE_USER"})
  @PreAuthorize("hasRole('ADMIN')")
  @RequestMapping(value = "/users", method = RequestMethod.GET)
  public List<User> listUser() {
    return userService.findAll();
  }

  // @Secured("ROLE_USER")
  @PreAuthorize("hasRole('USER')")
  //// @PreAuthorize("hasAnyRole('USER', 'ADMIN')")
  @RequestMapping(value = "/users/{id}", method = RequestMethod.GET)
  public User getOne(@PathVariable(value = "id") Long id) {
    return userService.findById(id);
  }
}
上一页