// this is embedded in blog post https://phip1611.de/?p=9898
/*
Copyright 2018 Philipp Schuster
Web: phip1611.de
Twitter: @phip1611
*/
package de.phips_photoblog.controller;
import de.phips_photoblog.controller.dto.UserDto;
import de.phips_photoblog.service.api.TokenService;
import de.phips_photoblog.service.api.UserService;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.UUID;
/**
* Rest-Controller used for creating an login and verifying the user token. Also giving the
* current active user dto to the client.
*/
@RestController
@RequestMapping("api/auth")
public class AuthController {
public AuthController() {
}
/**
* This endpoint is used by clients to do a login. They send a basic http auth
* request to this service and spring security makes the magic. (see config).
* If this method got actually invoked it means that spring security authenticated
* the user. It returns the secret id (token) that the client needs to use for
* all further requests.
* @param authentication Authenticated User
* @return token
*/
@GetMapping(path = "/login")
public UUID getToken(Authentication authentication) {
return (UUID)authentication.getCredentials();
}
/**
* Endpoint for testing the token. If it works, it returns the current active user
* to the client. Only get's invoked if spring security verifies the request
* (or if something went horribly wrong with spring security config)
*
* It returns the current authenticated principal (userdto)
*
* @return Principal (UserDto)
*/
@GetMapping(path = "/token")
public UserDto getUserDtoOfAuthenticatedUser(Authentication authentication) {
return (UserDto)authentication.getPrincipal();
}
}