@RestSchema(schemaId = "authenticationRestEndpoint")
@Controller
@RequestMapping("/rest")
public class AuthenticationController {
private static final Logger logger = LoggerFactory.getLogger(AuthenticationController.class);
static final String USERNAME = "username";
static final String PASSWORD = "password";
static final String TOKEN = "token";
private final AuthenticationService authenticationService;
@Autowired
AuthenticationController(AuthenticationService authenticationService) {
this.authenticationService = authenticationService;
}
@RequestMapping(value = "/login", method = POST, produces = TEXT_PLAIN_VALUE)
public ResponseEntity<String> login(
@RequestParam(USERNAME) String username,
@RequestParam(PASSWORD) String password) {
logger.info("Received login request from user {}", username);
String token = authenticationService.authenticate(username, password);
HttpHeaders headers = new HttpHeaders();
headers.add(AUTHORIZATION, TOKEN_PREFIX + token);
logger.info("Authenticated user {} successfully", username);
return new ResponseEntity<>("Welcome, " + username, headers, OK);
}
@RequestMapping(value = "/validate", method = POST, consumes = APPLICATION_JSON_UTF8_VALUE, produces = TEXT_PLAIN_VALUE)
@ResponseBody
public String validate(@RequestBody Token token) {
logger.info("Received validation request of token {}", token);
return authenticationService.validate(token.getToken());
}
}
class Token {
private String token;
Token() {
}
Token(String token) {
this.token = token;
}
public String getToken() {
return token;
}
@Override
public String toString() {
return "Token{" +
"token='" + token + '\'' +
'}';
}
}
评论