change json api demo endpoint to only allow access to super user. Token is now obtained from chat endpoint

This commit is contained in:
Rohan Sircar 2019-11-23 10:25:06 +05:30
parent d26ea2749e
commit 493d3cd079
4 changed files with 29 additions and 24 deletions

View File

@ -69,8 +69,12 @@ public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
// .cors().and() // .cors().and()
.antMatcher("/api/**").authorizeRequests() .antMatcher("/api/**").authorizeRequests()
.antMatchers("/api/chat/**").hasAnyRole("USER", "ADMIN", "SUPER_USER")
.antMatchers("/api/demo/**").hasRole("SUPER_USER")
// .antMatchers("/perform-login").permitAll() // .antMatchers("/perform-login").permitAll()
.anyRequest() .anyRequest()
// .hasAnyRole("USER", "ADMIN", "SUPER_USER") // .hasAnyRole("USER", "ADMIN", "SUPER_USER")
.authenticated().and().httpBasic().authenticationEntryPoint(authenticationEntryPoint) .authenticated().and().httpBasic().authenticationEntryPoint(authenticationEntryPoint)

View File

@ -44,8 +44,8 @@ public class ChatMessageController {
@PostMapping(value = "/post/message", consumes = { "application/json" }) @PostMapping(value = "/post/message", consumes = { "application/json" })
@ResponseBody @ResponseBody
public ResponseEntity<?> newMessage(@RequestBody @Valid ChatMessageDTO chatMessageDTO, public ResponseEntity<?> newMessage(@RequestBody @Valid ChatMessageDTO chatMessageDTO, BindingResult bindingResult,
BindingResult bindingResult, Principal principal) { Principal principal) {
if (bindingResult.hasErrors()) { if (bindingResult.hasErrors()) {
// return new ResponseEntity<List<FieldError>>(bindingResult.getFieldErrors(),HttpStatus.BAD_REQUEST); // return new ResponseEntity<List<FieldError>>(bindingResult.getFieldErrors(),HttpStatus.BAD_REQUEST);
@ -60,36 +60,33 @@ public class ChatMessageController {
} }
/** /**
* Method that check against {@code @Valid} Objects passed to controller endpoints * Method that check against {@code @Valid} Objects passed to controller
* endpoints
* *
* @param exception * @param exception
* @return a {@code ErrorResponse} * @return a {@code ErrorResponse}
* @see com.aroussi.util.validation.ErrorResponse * @see com.aroussi.util.validation.ErrorResponse
*/ */
@ExceptionHandler(value=MethodArgumentNotValidException.class) @ExceptionHandler(value = MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse handleException(MethodArgumentNotValidException exception) { public ErrorResponse handleException(MethodArgumentNotValidException exception) {
List<ErrorModel> errorMessages = exception.getBindingResult().getFieldErrors().stream() List<ErrorModel> errorMessages = exception.getBindingResult().getFieldErrors().stream()
.map(err -> new ErrorModel(err.getField(), err.getRejectedValue(), err.getDefaultMessage())) .map(err -> new ErrorModel(err.getField(), err.getRejectedValue(), err.getDefaultMessage())).distinct()
.distinct() .collect(Collectors.toList());
.collect(Collectors.toList()); return ErrorResponse.builder().errorMessage(errorMessages).build();
return ErrorResponse.builder().errorMessage(errorMessages).build();
} }
@ExceptionHandler(value=MethodArgumentNotValidException.class) @ExceptionHandler(value = MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse handleException(BindingResult bindingResult) { public ErrorResponse handleException(BindingResult bindingResult) {
List<ErrorModel> errorMessages = bindingResult.getFieldErrors().stream() List<ErrorModel> errorMessages = bindingResult.getFieldErrors().stream()
.map(err -> new ErrorModel(err.getField(), err.getRejectedValue(), err.getDefaultMessage())) .map(err -> new ErrorModel(err.getField(), err.getRejectedValue(), err.getDefaultMessage())).distinct()
.distinct() .collect(Collectors.toList());
.collect(Collectors.toList()); return ErrorResponse.builder().errorMessage(errorMessages).build();
return ErrorResponse.builder().errorMessage(errorMessages).build();
} }
@GetMapping(value = "/get/messages/{userName}") @GetMapping(value = "/get/messages/{userName}")
@ResponseBody @ResponseBody
public List<ChatMessageDTO> sendAllMessages(@PathVariable String userName, Principal principal) { public List<ChatMessageDTO> sendAllMessages(@PathVariable String userName, Principal principal) {
@ -136,6 +133,11 @@ public class ChatMessageController {
public List<ActiveUserDTO> getAllOtherActiveUsers(Principal principal) { public List<ActiveUserDTO> getAllOtherActiveUsers(Principal principal) {
return userService.getOtherActiveUsers(principal.getName()); return userService.getOtherActiveUsers(principal.getName());
} }
@GetMapping("/get/token")
public ResponseEntity<?> getToken() {
return new ResponseEntity<String>(HttpStatus.OK);
}
} }
//public ResponseEntity<List<ChatMessage>> getMessages(@PathVariable String userName, Principal principal) { //public ResponseEntity<List<ChatMessage>> getMessages(@PathVariable String userName, Principal principal) {

View File

@ -33,7 +33,7 @@ import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
@RestController @RestController
@RequestMapping("/api") @RequestMapping("/api/demo")
//@CrossOrigin(origins = "*", allowCredentials = "true", allowedHeaders = "*") //@CrossOrigin(origins = "*", allowCredentials = "true", allowedHeaders = "*")
public class DemoRestController { public class DemoRestController {

View File

@ -10,8 +10,7 @@ function storeCredentials() {
var jqxhr = $.ajax({ var jqxhr = $.ajax({
type: 'GET', type: 'GET',
url: `http://${hostAddress}/api/user`, url: `http://${hostAddress}/api/chat/get/token`,
dataType: 'json',
headers: { headers: {
"Authorization": "Basic " + btoa(usernameInput.value + ":" + passwordInput.value) "Authorization": "Basic " + btoa(usernameInput.value + ":" + passwordInput.value)
}, },