繁体   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