簡體   English   中英

如何在不將它們傳遞給API方法調用的情況下獲取Spring REST Controller中的用戶/主體/身份驗證句柄?

[英]How to get a handle to the User/Principal/Authentication in Spring REST Controller without passing them to the API method call?

我正在使用Spring 4.2.6.RELEASE和Spring Security4.x。 我想知道是否有可能在不將WebRequest或任何其他Spring對象傳遞到REST API調用的方法中的情況下,獲得Spring REST Controller中的User(Principal)對象的句柄,例如在getBanks中(WebRequest pWebRequest)

我目前正在使用傳遞給方法的WebRequest在Spring中獲取用戶詳細信息。 這正在影響我的REST文檔定義,尤其是在使用SWAGGER生成YAML文件時。

是否可以注入或獲取主體或用戶的句柄,而不必將其傳遞給REST API方法調用,並且仍然保留我API的安全性。

@RestController
@RequestMapping(value = "/banks", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class BankResource extends Resource {

@RequestMapping(value = "/banks", method = RequestMethod.GET)
public ResponseEntity<List<Banks>> getBanks(WebRequest pWebRequest) {

Authentication authentication = (Authentication) pWebRequest.getUserPrincipal();
Object principal = pAuthentication != null ? pAuthentication.getPrincipal() : null;
User user = (User) principal;
BankCriteria criteria = new BankCriteria();
List<Bank> banks = _bankService.getBanks(user, criteria);
return ResponseEntity.ok(banks);
}

您可以將身份驗證作為參數:

public ResponseEntity<List<Banks>> getBanks(Authentication auth) {
...
}

或者,您可以通過controller方法內的靜態方法調用來獲取它:

Authentication auth = SecurityContextHolder.getContext().getAuthentication();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM