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

The following examples show how to use org.springframework.security.core.annotation.AuthenticationPrincipal. 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 File: OrderController.java    From spring-in-action-5-samples with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: ConfigPropertyController.java    From pacbot with 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 #3
Source File: UserController.java    From cola with 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 #4
Source File: OrderController.java    From spring-in-action-5-samples with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: OrderController.java    From spring-in-action-5-samples with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: OrderController.java    From spring-in-action-5-samples with Apache License 2.0 6 votes vote down vote up
@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 #7
Source File: OrderController.java    From spring-in-action-5-samples with Apache License 2.0 6 votes vote down vote up
@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 #8
Source File: OrderController.java    From spring-in-action-5-samples with Apache License 2.0 6 votes vote down vote up
@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 #9
Source File: OrderController.java    From spring-in-action-5-samples with Apache License 2.0 6 votes vote down vote up
@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
Source File: OrderController.java    From spring-in-action-5-samples with Apache License 2.0 6 votes vote down vote up
@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
Source File: OrderController.java    From spring-in-action-5-samples with Apache License 2.0 6 votes vote down vote up
@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
Source File: TestController.java    From cloud-security-xsuaa-integration with Apache License 2.0 6 votes vote down vote up
/**
 * 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
Source File: OrderController.java    From spring-in-action-5-samples with Apache License 2.0 6 votes vote down vote up
@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
Source File: OrderController.java    From spring-in-action-5-samples with Apache License 2.0 6 votes vote down vote up
@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 #15
Source File: SpendController.java    From kid-bank with 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 #16
Source File: OrderController.java    From spring-in-action-5-samples with Apache License 2.0 6 votes vote down vote up
@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 #17
Source File: ExamController.java    From java-master with 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 #18
Source File: UserController.java    From java-master with 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 File: TestController.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
@GetMapping("/user")
public String message(@AuthenticationPrincipal Token token) {
	// attributes - old style
	Assert.assertEquals(2, token.getXSUserAttribute("cost-center").length);
	Assert.assertEquals("0815", token.getXSUserAttribute("cost-center")[0]);
	Assert.assertEquals("4711", token.getXSUserAttribute("cost-center")[1]);
	Assert.assertEquals(1, token.getXSUserAttribute("country").length);
	Assert.assertEquals("Germany", token.getXSUserAttribute("country")[0]);
	// client id
	Assert.assertEquals("sb-java-hello-world", token.getClientId());
	// grant type
	Assert.assertEquals("authorization_code", token.getGrantType());

	// logon name
	Assert.assertEquals("Mustermann", token.getLogonName());
	// email
	Assert.assertEquals("[email protected]", token.getEmail());
	// zone
	Assert.assertTrue(token.getZoneId().endsWith("domain-id"));
	// ext attr
	Assert.assertEquals("domain\\group1", token.getAdditionalAuthAttribute("external_group"));
	Assert.assertEquals("abcd1234", token.getAdditionalAuthAttribute("external_id"));

	// service instance id
	Assert.assertEquals("abcd1234", token.getCloneServiceInstanceId());

	return "user:" + token.getLogonName();
}
 
Example #20
Source File: OrderController.java    From spring-in-action-5-samples with Apache License 2.0 5 votes vote down vote up
@GetMapping
public String ordersForUser(
    @AuthenticationPrincipal User user, Model model) {

  Pageable pageable = PageRequest.of(0, props.getPageSize());
  model.addAttribute("orders", 
      orderRepo.findByUserOrderByPlacedAtDesc(user, pageable));
  
  return "orderList";
}
 
Example #21
Source File: TestController.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
@GetMapping("/requesttoken")
public String requestToken(@AuthenticationPrincipal Token token) throws TokenFlowException {
	Map<String, String> azMape = new HashMap();
	azMape.put("a", "b");
	azMape.put("c", "d");

	XsuaaTokenFlows tokenFlows = new XsuaaTokenFlows(new XsuaaOAuth2TokenService(new RestTemplate()),
			new XsuaaDefaultEndpoints(serviceConfiguration.getUaaUrl()), new ClientCredentials("c1", "s1"));
	ClientCredentialsTokenFlow ccTokenFlow = tokenFlows.clientCredentialsTokenFlow().attributes(azMape)
			.subdomain(token.getSubdomain());

	OAuth2TokenResponse newToken = ccTokenFlow.execute();
	return newToken.getAccessToken();
}
 
Example #22
Source File: OrderController.java    From spring-in-action-5-samples with Apache License 2.0 5 votes vote down vote up
@GetMapping
public String ordersForUser(
    @AuthenticationPrincipal User user, Model model) {

  Pageable pageable = PageRequest.of(0, props.getPageSize());
  model.addAttribute("orders", 
      orderRepo.findByUserOrderByPlacedAtDesc(user, pageable));
  
  return "orderList";
}
 
Example #23
Source File: TravelGatewayApplication.java    From spring-security-samples with 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 #24
Source File: ArticleController.java    From Spring-Boot-2.0-Projects with 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 #25
Source File: OrderController.java    From spring-in-action-5-samples with Apache License 2.0 5 votes vote down vote up
@GetMapping
public String ordersForUser(
    @AuthenticationPrincipal User user, Model model) {

  Pageable pageable = PageRequest.of(0, props.getPageSize());
  model.addAttribute("orders", 
      orderRepo.findByUserOrderByPlacedAtDesc(user, pageable));
  
  return "orderList";
}
 
Example #26
Source File: SecuredServiceApplication.java    From spring-cloud-gateway-demo with Apache License 2.0 5 votes vote down vote up
@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 #27
Source File: TestController.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
/**
 * REST endpoint showing how to retrieve an access token for a refresh token from XSUAA using the
 * {@link XsuaaTokenFlows} API.
 * @param jwt - the Jwt as a result of authentication.
 * @param refreshToken - the refresh token an access token is requested
 * @throws TokenFlowException in case of any errors.
 */
@GetMapping("/v3/requestRefreshToken/{refreshToken}")
public String requestRefreshToken(@AuthenticationPrincipal Jwt jwt, @PathVariable("refreshToken") String refreshToken) throws TokenFlowException {

    OAuth2TokenResponse refreshTokenResponse = tokenFlows.refreshTokenFlow()
    		.refreshToken(refreshToken)
            .execute();
 
    logger.info("Got the access token for the refresh token: {}", refreshTokenResponse.getAccessToken());
    logger.info("You could now inject this into Spring's SecurityContext, using: SpringSecurityContext.init(...).");

    return refreshTokenResponse.getDecodedAccessToken().getPayload();
}
 
Example #28
Source File: ArticleController.java    From Spring-Boot-2.0-Projects with 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 #29
Source File: ClusterScaleController.java    From cymbal with 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 File: RSocketController.java    From spring-rsocket-demo with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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)));
}