Java Code Examples for org.springframework.security.core.annotation.AuthenticationPrincipal

The following examples show how to use org.springframework.security.core.annotation.AuthenticationPrincipal. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: cola   Source File: UserController.java    License: MIT License 6 votes vote down vote up
@ApiOperation(value = "绑定手机号码")
@PostMapping("/bindPhoneNumber")
public Result<String> bindPhoneNumber(@RequestBody @Valid @ApiParam("绑定手机号参数") PhoneNumberBindDto binding,
									  @AuthenticationPrincipal AuthenticatedUser authenticatedUser) {

	CredentialValidation validation = CredentialValidation.builder()
			.application("sign_up")
			.principal(binding.getPhoneNumber())
			.token(binding.getToken())
			.credential(binding.getCredential())
			.ignoreCase(true)
			.build();
	//验证短信验证码
	ServiceAssert.isTrue(credentialService.validate(validation), UserErrorMessage.SMS_CREDENTIAL_NOT_MATCHED);

	this.userService.updatePhoneNumber(authenticatedUser.getId(), binding.getPhoneNumber());

	return Result.success();
}
 
Example 2
Source Project: kid-bank   Source File: SpendController.java    License: Apache License 2.0 6 votes vote down vote up
@PostMapping
public String processSpendCommand(
    @Valid @ModelAttribute("spendCommand") TransactionCommand spendDto,
    BindingResult bindingResult,
    @AuthenticationPrincipal UserProfile userProfile) {
  if (bindingResult.hasErrors()) {
    return "spend";
  }

  int spendAmount = spendDto.amountInCents();
  LocalDateTime dateTime = spendDto.getDateAsLocalDateTime();

  account.spend(dateTime, spendAmount, spendDto.getDescription(), userProfile);

  return "redirect:" + AccountController.ACCOUNT_URL;
}
 
Example 3
@GetMapping("/current")
public String orderForm(@AuthenticationPrincipal User user, 
    @ModelAttribute Order order) {
  if (order.getDeliveryName() == null) {
    order.setDeliveryName(user.getFullname());
  }
  if (order.getDeliveryStreet() == null) {
    order.setDeliveryStreet(user.getStreet());
  }
  if (order.getDeliveryCity() == null) {
    order.setDeliveryCity(user.getCity());
  }
  if (order.getDeliveryState() == null) {
    order.setDeliveryState(user.getState());
  }
  if (order.getDeliveryZip() == null) {
    order.setDeliveryZip(user.getZip());
  }
  
  return "orderForm";
}
 
Example 4
@PostMapping
public String processOrder(@Valid Order order, Errors errors, 
    SessionStatus sessionStatus, 
    @AuthenticationPrincipal User user) {
  
  if (errors.hasErrors()) {
    return "orderForm";
  }

  order.setUser(user);
  
  orderRepo.save(order);
  sessionStatus.setComplete();
  
  return "redirect:/";
}
 
Example 5
@GetMapping("/current")
public String orderForm(@AuthenticationPrincipal User user, 
    @ModelAttribute Order order) {
  if (order.getDeliveryName() == null) {
    order.setDeliveryName(user.getFullname());
  }
  if (order.getDeliveryStreet() == null) {
    order.setDeliveryStreet(user.getStreet());
  }
  if (order.getDeliveryCity() == null) {
    order.setDeliveryCity(user.getCity());
  }
  if (order.getDeliveryState() == null) {
    order.setDeliveryState(user.getState());
  }
  if (order.getDeliveryZip() == null) {
    order.setDeliveryZip(user.getZip());
  }
  
  return "orderForm";
}
 
Example 6
@PostMapping
public String processOrder(@Valid Order order, Errors errors, 
    SessionStatus sessionStatus, 
    @AuthenticationPrincipal User user) {
  
  if (errors.hasErrors()) {
    return "orderForm";
  }

  UserUDT userUDT = new UserUDT(user.getUsername(), user.getFullname(), user.getPhoneNumber());
  order.setUser(userUDT);
  
  orderRepo.save(order);
  sessionStatus.setComplete();
  
  return "redirect:/";
}
 
Example 7
@GetMapping("/current")
public String orderForm(@AuthenticationPrincipal User user, 
    @ModelAttribute Order order) {
  if (order.getDeliveryName() == null) {
    order.setDeliveryName(user.getFullname());
  }
  if (order.getDeliveryStreet() == null) {
    order.setDeliveryStreet(user.getStreet());
  }
  if (order.getDeliveryCity() == null) {
    order.setDeliveryCity(user.getCity());
  }
  if (order.getDeliveryState() == null) {
    order.setDeliveryState(user.getState());
  }
  if (order.getDeliveryZip() == null) {
    order.setDeliveryZip(user.getZip());
  }
  
  return "orderForm";
}
 
Example 8
@PostMapping
public String processOrder(@Valid Order order, Errors errors, 
    SessionStatus sessionStatus, 
    @AuthenticationPrincipal User user) {
  
  if (errors.hasErrors()) {
    return "orderForm";
  }
  
  order.setUser(user);
  
  orderRepo.save(order);
  sessionStatus.setComplete();
  
  return "redirect:/";
}
 
Example 9
@GetMapping("/current")
public String orderForm(@AuthenticationPrincipal User user, 
    @ModelAttribute Order order) {
  if (order.getDeliveryName() == null) {
    order.setDeliveryName(user.getFullname());
  }
  if (order.getDeliveryStreet() == null) {
    order.setDeliveryStreet(user.getStreet());
  }
  if (order.getDeliveryCity() == null) {
    order.setDeliveryCity(user.getCity());
  }
  if (order.getDeliveryState() == null) {
    order.setDeliveryState(user.getState());
  }
  if (order.getDeliveryZip() == null) {
    order.setDeliveryZip(user.getZip());
  }
  
  return "orderForm";
}
 
Example 10
@PostMapping
public String processOrder(@Valid Order order, Errors errors, 
    SessionStatus sessionStatus, 
    @AuthenticationPrincipal User user) {
  
  if (errors.hasErrors()) {
    return "orderForm";
  }
  
  order.setUser(user);
  
  orderRepo.save(order);
  sessionStatus.setComplete();
  
  return "redirect:/";
}
 
Example 11
@GetMapping("/current")
public String orderForm(@AuthenticationPrincipal User user, 
    @ModelAttribute Order order) {
  if (order.getDeliveryName() == null) {
    order.setDeliveryName(user.getFullname());
  }
  if (order.getDeliveryStreet() == null) {
    order.setDeliveryStreet(user.getStreet());
  }
  if (order.getDeliveryCity() == null) {
    order.setDeliveryCity(user.getCity());
  }
  if (order.getDeliveryState() == null) {
    order.setDeliveryState(user.getState());
  }
  if (order.getDeliveryZip() == null) {
    order.setDeliveryZip(user.getZip());
  }
  
  return "orderForm";
}
 
Example 12
/**
 * Returns the detailed information of the XSUAA JWT token.
 * Uses a Token retrieved from the security context of Spring Security.
 *
 * @param token the XSUAA token from the request injected by Spring Security.
 * @return the requested address.
 * @throws Exception in case of an internal error.
 */
@GetMapping("/v1/sayHello")
public Map<String, String> sayHello(@AuthenticationPrincipal Token token) {

    logger.info("Got the Xsuaa token: {}", token.getAppToken());
    logger.info(token.toString());

    Map<String, String> result = new HashMap<>();
    result.put("grant type", token.getGrantType());
    result.put("client id", token.getClientId());
    result.put("subaccount id", token.getSubaccountId());
    result.put("zone id", token.getZoneId());
    result.put("logon name", token.getLogonName());
    result.put("family name", token.getFamilyName());
    result.put("given name", token.getGivenName());
    result.put("email", token.getEmail());
    result.put("authorities", String.valueOf(token.getAuthorities()));
    result.put("scopes", String.valueOf(token.getScopes()));

    return result;
}
 
Example 13
@GetMapping("/current")
public String orderForm(@AuthenticationPrincipal User user, 
    @ModelAttribute Order order) {
  if (order.getDeliveryName() == null) {
    order.setDeliveryName(user.getFullname());
  }
  if (order.getDeliveryStreet() == null) {
    order.setDeliveryStreet(user.getStreet());
  }
  if (order.getDeliveryCity() == null) {
    order.setDeliveryCity(user.getCity());
  }
  if (order.getDeliveryState() == null) {
    order.setDeliveryState(user.getState());
  }
  if (order.getDeliveryZip() == null) {
    order.setDeliveryZip(user.getZip());
  }
  
  return "orderForm";
}
 
Example 14
@GetMapping("/current")
public String orderForm(@AuthenticationPrincipal User user,
    @ModelAttribute Order order) {
  if (order.getDeliveryName() == null) {
    order.setDeliveryName(user.getFullname());
  }
  if (order.getDeliveryStreet() == null) {
    order.setDeliveryStreet(user.getStreet());
  }
  if (order.getDeliveryCity() == null) {
    order.setDeliveryCity(user.getCity());
  }
  if (order.getDeliveryState() == null) {
    order.setDeliveryState(user.getState());
  }
  if (order.getDeliveryZip() == null) {
    order.setDeliveryZip(user.getZip());
  }

  return "orderForm";
}
 
Example 15
@PostMapping
public String processOrder(@Valid Order order, Errors errors,
    SessionStatus sessionStatus,
    @AuthenticationPrincipal User user) {

  if (errors.hasErrors()) {
    return "orderForm";
  }

  order.setUser(user);

  orderRepo.save(order);
  sessionStatus.setComplete();

  return "redirect:/";
}
 
Example 16
Source Project: pacbot   Source File: ConfigPropertyController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Do config property rollback to timestamp.
 *
 * @param user the user
 * @param timestamp the timestamp
 * @param userMessage the user message
 * @return the response entity
 */
@ApiOperation(httpMethod = "PUT", value = "API to rollback config properties to a particular timestamp", response = Response.class, produces = MediaType.APPLICATION_JSON_VALUE)
// @PreAuthorize("@securityService.hasPermission(authentication)")
// @HystrixCommand
@RequestMapping(path = "/rollback", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> doConfigPropertyRollbackToTimestamp(@AuthenticationPrincipal Principal user,
		@ApiParam(value = "provide timestamp in yyyy-MM-dd HH:mm:ss", required = true) @RequestParam(defaultValue = "", name = "timestamp", required = true) String timestamp,
		@ApiParam(value = "provide a message for this rollback", required = false) @RequestParam(defaultValue = "", name = "userMessage", required = false) String userMessage) {
	try {
		return ResponseUtils.buildSucessResponse(
				configPropertyService.doConfigPropertyRollbackToTimestamp(timestamp, user.getName(), userMessage));
	} catch (Exception exception) {
		log.error(UNEXPECTED_ERROR_OCCURRED, exception);
		return ResponseUtils.buildFailureResponse(exception, null, null);
	}
}
 
Example 17
Source Project: Spring-Boot-2.0-Projects   Source File: ArticleController.java    License: MIT License 5 votes vote down vote up
@PostMapping("/delete/{id}")
public String deletePost(@AuthenticationPrincipal UserDetails userDetails, @PathVariable String id, Model model) {
    articleService.deleteById(id);

    model.addAttribute("message", "Article with id " + id + " deleted successfully!");
    model.addAttribute("articles", articleService.getAll(new PageRequest(0, 10)));

    return "article/index";
}
 
Example 18
Source Project: java-master   Source File: UserController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 拥有管理员权限可查看任何用户信息,否则只能查看自己的信息
 */
@PreAuthorize("hasAuthority('ROLE_DMIN') or #reqVo.sysUser.username == #userDetails.username")
@PostMapping("/findUsers")
public Result<List<SysUser>> findUsers(@RequestBody FindUsersReqVo reqVo, @AuthenticationPrincipal UserDetails userDetails) {
    PageInfo<SysUser> pageInfo = userService.findUsers(reqVo);
    return new Result<>(pageInfo.getList(), pageInfo.getTotal());
}
 
Example 19
Source Project: java-master   Source File: UserController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 拥有管理员权限可修改任何用户的密码,否则只能修改自己的密码
 */
@PreAuthorize("hasAuthority('ROLE_ADMIN') or (#reqVo.username == #userDetails.username and !T(org.springframework.util.StringUtils).isEmpty(#reqVo.password))")
@PostMapping("/updatePassword")
public Result<Integer> updatePassword(@Validated @RequestBody UpdatePasswordReqVo reqVo,
                                      @AuthenticationPrincipal UserDetails userDetails) {
    return new Result<>(userService.updatePassword(reqVo, userDetails));
}
 
Example 20
Source Project: java-master   Source File: ExamController.java    License: Apache License 2.0 5 votes vote down vote up
@PostMapping("/getExamList")
public Result<List<GetExamListResVo>> getExamList(@Validated @RequestBody GetExamListReqVo reqVo,
                                                  @AuthenticationPrincipal UserDetails userDetails)
        throws IOException {
    List<GetExamListResVo> resVos = examService.getExamList(reqVo, userDetails);
    return new Result<>(resVos);
}
 
Example 21
/**
 * This @MessageMapping is intended to be used "request --> response" style.
 * For each Message received, a new Message is returned with ORIGIN=Server and INTERACTION=Request-Response.
 *
 * @param request
 * @return Message
 */
@PreAuthorize("hasRole('USER')")
@MessageMapping("request-response")
Mono<Message> requestResponse(final Message request, @AuthenticationPrincipal UserDetails user) {
    log.info("Received request-response request: {}", request);
    log.info("Request-response initiated by '{}' in the role '{}'", user.getUsername(), user.getAuthorities());
    // create a single Message and return it
    return Mono.just(new Message(SERVER, RESPONSE));
}
 
Example 22
/**
 * This @MessageMapping is intended to be used "fire --> forget" style.
 * When a new CommandRequest is received, nothing is returned (void)
 *
 * @param request
 * @return
 */
@PreAuthorize("hasRole('USER')")
@MessageMapping("fire-and-forget")
public Mono<Void> fireAndForget(final Message request, @AuthenticationPrincipal UserDetails user) {
    log.info("Received fire-and-forget request: {}", request);
    log.info("Fire-And-Forget initiated by '{}' in the role '{}'", user.getUsername(), user.getAuthorities());
    return Mono.empty();
}
 
Example 23
/**
 * This @MessageMapping is intended to be used "subscribe --> stream" style.
 * When a new request command is received, a new stream of events is started and returned to the client.
 *
 * @param request
 * @return
 */
@PreAuthorize("hasRole('USER')")
@MessageMapping("stream")
Flux<Message> stream(final Message request, @AuthenticationPrincipal UserDetails user) {
    log.info("Received stream request: {}", request);
    log.info("Stream initiated by '{}' in the role '{}'", user.getUsername(), user.getAuthorities());

    return Flux
            // create a new indexed Flux emitting one element every second
            .interval(Duration.ofSeconds(1))
            // create a Flux of new Messages using the indexed Flux
            .map(index -> new Message(SERVER, STREAM, index));
}
 
Example 24
/**
 * This @MessageMapping is intended to be used "stream <--> stream" style.
 * The incoming stream contains the interval settings (in seconds) for the outgoing stream of messages.
 *
 * @param settings
 * @return
 */
@PreAuthorize("hasRole('USER')")
@MessageMapping("channel")
Flux<Message> channel(final Flux<Duration> settings, @AuthenticationPrincipal UserDetails user) {
    log.info("Received channel request...");
    log.info("Channel initiated by '{}' in the role '{}'", user.getUsername(), user.getAuthorities());

    return settings
            .doOnNext(setting -> log.info("Channel frequency setting is {} second(s).", setting.getSeconds()))
            .doOnCancel(() -> log.warn("The client cancelled the channel."))
            .switchMap(setting -> Flux.interval(setting)
                    .map(index -> new Message(SERVER, CHANNEL, index)));
}
 
Example 25
Source Project: spring-security-samples   Source File: TravelGatewayApplication.java    License: MIT License 5 votes vote down vote up
@GetMapping("/whoami")
@ResponseBody
public Map<String, Object> index(
		@RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient,
		@AuthenticationPrincipal OidcUser oidcUser) {
	Map<String, Object> model = new HashMap<>();
	model.put("clientName", authorizedClient.getClientRegistration().getClientName());
	model.put("userName", oidcUser.getName());
	model.put("userAttributes", oidcUser.getAttributes());
	return model;
}
 
Example 26
Source Project: Spring-Boot-2.0-Projects   Source File: ArticleController.java    License: MIT License 5 votes vote down vote up
@PostMapping
public String savePost(@AuthenticationPrincipal UserDetails userDetails, Article article, Model model) {
    if (article.getId() == null || article.getId().length() == 0) {
        User user = userService.getByUsername(userDetails.getUsername());
        article.setAuthor(user);
    } else {
        Optional<Article> optionalArticle = articleService.getById(article.getId());
        if (optionalArticle.isPresent()) {
            article.setAuthor(optionalArticle.get().getAuthor());
        }
    }
    articleService.save(article);

    return "redirect:/article/show/"+article.getLink();
}
 
Example 27
@GetMapping("/resource")
public String resource(@AuthenticationPrincipal Jwt jwt) {
  LOG.trace("***** JWT Headers: {}", jwt.getHeaders());
  LOG.trace("***** JWT Claims: {}", jwt.getClaims().toString());
  LOG.trace("***** JWT Token: {}", jwt.getTokenValue());
  return String.format("Resource accessed by: %s (with subjectId: %s)" ,
          jwt.getClaims().get("user_name"),
          jwt.getSubject());
}
 
Example 28
Source Project: cymbal   Source File: ApplicationFormController.java    License: Apache License 2.0 5 votes vote down vote up
@PostMapping(value = "/application-forms")
@ResponseBody
public void createApplicationForm(@RequestBody ApplicationForm applicationForm,
        @AuthenticationPrincipal Principal principal) {
    if (Objects.isNull(applicationForm.getApplicantEnName())) {
        applicationForm.setApplicantEnName(principal.getName());
        applicationForm.setApplicantCnName(userProcessService.getUserCnName(principal.getName()));
    }
    applicationFormProcessService.saveRedisApplicationForm(applicationForm);
}
 
Example 29
Source Project: cymbal   Source File: ClusterScaleController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create and do cluster scale.
 *
 * @param clusterId cluster id
 * @param clusterScaleDTO cluster scale DTO
 * @return http response entity
 */
@PostMapping("/clusters/{clusterId}/scales")
@PreAuthorize("hasRole('ADMIN')")
@ResponseBody
public ResponseEntity<String> doScale(final @PathVariable String clusterId,
        final @RequestBody ClusterScaleDTO clusterScaleDTO, final @AuthenticationPrincipal Principal principal) {
    ClusterScale clusterScale = clusterScaleConverter.dtoToPo(clusterScaleDTO);
    clusterScale.setOperator(principal.getName());
    try {
        redisClusterScaleProcessService.doScale(clusterScale);
        return ResponseEntity.ok().build();
    } catch (NotEnoughResourcesException e) {
        return ResponseEntity.badRequest().build();
    }
}
 
Example 30
Source Project: blog-tutorials   Source File: GitHubController.java    License: MIT License 5 votes vote down vote up
@GetMapping
public String index(@RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient,
                    @AuthenticationPrincipal OAuth2User oauth2User,
                    Model model) {

    model.addAttribute("repositories", fetchAllRepositories(authorizedClient));
    model.addAttribute("username", oauth2User.getAttributes().get("login"));

    return "index";
}