简体   繁体   English

使用 Spring Security 对用户进行身份验证

[英]Authenticate user with Spring Security

Assume we have endpoint like this /users/{userId}/messages/{messageId} and which is exposed via @DeleteMapping (as endpoint suggest's, it delete's message with specified ID, for specified user).假设我们有这样的端点/users/{userId}/messages/{messageId}并且它通过@DeleteMapping (正如端点建议的那样,它删除具有指定 ID 的消息,用于指定用户)。 Message can be deleted in two cases: you are moderator, or you are owner of the message.可以在两种情况下删除Message :您是版主,或者您是消息的所有者。 The first part is quiet easy, you can add in Security configuration that you need ROLE_MODERATOR to use this endoint.第一部分很简单,你可以在Security configuration中添加你需要ROLE_MODERATOR来使用这个端点。 But there is second case, when you can delete message if you are owner.但是还有第二种情况,如果您是所有者,则可以删除消息。 How to implement it properly?如何正确实施? If you add ROLE_MODERATOR in Security configuration you are disabling enpoint for non moderator users (including some owners of message).如果您在Security configuration添加ROLE_MODERATOR ,您将禁用非主持人用户(包括某些消息所有者)的 enpoint。 Assume we have service called AuthenticatedUserHolder with method getLoggedUserID() which will return userID (session, JWT or sth).假设我们有一个名为AuthenticatedUserHolder服务,其方法是getLoggedUserID() ,它将返回userID (会话、JWT 或 sth)。 Is there any way to combine ROLE_MODERATOR or message owner?有没有办法组合ROLE_MODERATOR或消息所有者?
Second question: Assume we have endpoint /users/{id}/addresses with @PutMapping and you can change address only if loggedUserID == id .第二个问题:假设我们有带有@PutMapping端点/users/{id}/addresses并且只有当loggedUserID == id您才能更改地址。 How to extract logic from service/facade that will return 401/403 if loggedUserID != id ?如何从service/facade中提取逻辑,如果loggedUserID != id将返回401/403

Edit: Method code:编辑:方法代码:

SecurityContext authentication = SecurityContextHolder.getContext();
    UserPrincipal loggedUser = (UserPrincipal) authentication.getAuthentication().getPrincipal();
    return loggedUser.getUser().getPersonId();

UserPrincipal has extra field personId . UserPrincipal 有额外的字段personId

You can use @PreAuthorize annotation with a custom method Examples您可以将 @PreAuthorize 注释与自定义方法一起使用示例

Controller控制器

@PreAuthorize("@beanName.beanMethodName(#controllerParamName)")
@GetMapping("/{controllerParamName}")
fun getMethod(@PathVariable("controllerParamName") param: Long) {
    //whenever
}

Validation Bean验证豆

@Service
class BeanName {
   fun beanMethodName(param: Long): Boolean {
      return false
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM