简体   繁体   English

Spring Security 角色 - 用户只能更改自己的数据?

[英]Spring Security Role - user can change only own data?

I start to use Spring Security.我开始使用 Spring Security。 For now I seting that user must login if they wont create table.现在我设置该用户必须登录,如果他们不创建表。 Or, for example, in the ControllerClass I configured to only user with role ROLE_USER can delete a table.或者,例如,在我配置为只有角色 ROLE_USER 的用户可以删除表的 ControllerClass 中。

My question is, in which way I can set that, when user login and he create some table and create teamPlayers , that the table or players can only edit or delete user who did create the table and the players.我的问题是,我可以通过哪种方式设置,当用户登录并创建一些表并创建 teamPlayers 时,表或玩家只能编辑或删除创建表和玩家的用户。

for example , I have in Controller method for delete table ...例如,我在控制器方法中删除表...

@RestController
@RequestMapping(value="/api/tables")
public class ApiTableController {

@Autowired
TableService tableService;
@Autowired
TableConverter tableConverter;

@PreAuthorize("hasRole('ROLE_USER')")    
@RequestMapping(value="/{id}", method=RequestMethod.DELETE)
public ResponseEntity<TableDTO> deleteTable(@PathVariable Long id) {
    Table table = tableService.findOne(id);
    if (table != null) {
        TableDTO tableDTO = tableConverter.table2TableDTO(table);
        tableService.remove(id);
        return new ResponseEntity<>(tableDTO, HttpStatus.OK);
    } else {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}

In this case, all users with role ROLE_USER can delete all table , but I wont to can delete table only user how created table ... Is there any rule how it works or standard code?在这种情况下,具有角色 ROLE_USER 的所有用户都可以删除所有表,但我不会只删除表用户如何创建表......它的工作原理或标准代码有什么规则吗? Like a profil on StackOwerflow .就像 StackOwerflow 上的简介一样。 Everyone can see what we write ,Everyone can create profil and only I can edit my profil or my quastions which I wrote on the site.每个人都可以看到我们写的内容,每个人都可以创建个人资料,只有我可以编辑我在网站上写的个人资料或我的问题。 How I can do somthing like that with Spring security?我怎么能用 Spring 安全做这样的事情?

this is class User这是用户类

@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue
@NotNull
@Column(name = "user_id")
private Long id;
@Column(name = "username")
private String name;
@Column(name = "password")
private String password;
@Column(name = "email")
private String email;
@Column(name = "country")
private String country;
@Column(name = "city")
private String city;
@Column(name = "dateCreated")
private Date dateCreated;
@Column(name = "enabled")
private boolean active;
@JoinTable(name = "user_security_role", joinColumns = { @JoinColumn(name = "user_id", 
referencedColumnName = "user_id") }, inverseJoinColumns = { 
@JoinColumn(name = "security_role_id", referencedColumnName = "id") })
@ManyToMany
private Set<SecurityRoleUser> securityRoleCollection;


@Override
public int hashCode() {

    int hash = 0;

    hash += (id != null ? id.hashCode() : 0);

    return hash;

}

@Override
public boolean equals(Object object) {

    if (!(object instanceof User)) {

        return false;

    }

    User other = (User) object;

    if ((this.id == null && other.id != null)
            || (this.id != null && !this.id.equals(other.id))) {

        return false;

    }

    return true;

}

And this is class Table ...这是班级表......

@Entity
@javax.persistence.Table(name="tblTable")
public class Table {
@Id
@GeneratedValue
@Column(name="table_id")
private Long id;
@Column(name="name", nullable=true)
private String name;
@Column(name="sport", nullable=true)
private String sport;
@Column(name="typeTable", nullable=true)
private String TypeTable;
@Column(name="dateCreated", nullable=true)
private Date dateCreated;
@Column(name="changed", nullable=true)
private Date changed;
@Column(name="description", nullable=true)
private String description;

I use hibernate, maven, RESTFull web server, backbone.js....我使用休眠、maven、RESTFull Web 服务器、backbone.js ....

Not really an detailed answer but allready too long for a comment.不是很详细的答案,但已经太久了,无法发表评论。

Spring security comes with a feature that is exactly what you need : Domain Object Security or ACLs Spring 安全性附带的功能正是您所需要的: 域对象安全性或 ACL

It's a rather advanced feature because if needs to add a set of tables to represents the authorizations of users on every secured domain object.这是一个相当高级的功能,因为如果需要添加一组表来表示用户对每个安全域对象的授权。 One for the object classes, one for the objects themselves (only primary key is stored) and others for actual authorizations.一种用于对象类,一种用于对象本身(仅存储主键),另一种用于实际授权。 In fact, it can be seen as the authorizations on a shared filesystem.实际上,它可以看作是对共享文件系统的授权。

You normaly use then method security with @PreAuthorize annotation that allows to use an expression containing the actual parameters of the method.您通常使用带有@PreAuthorize批注的 then 方法安全性, @PreAuthorize批注允许使用包含方法实际参数的表达式。 You directly allow a user to modify, or delete each and every domain object.您直接允许用户修改或删除每个域对象。

In addition to the Spring Security Reference Manual already cited above, you can find a complete tutorial on ACLs on krams::: Spring Security 3: Full ACL Tutorial .除了上面已经引用的 Spring Security 参考手册之外,您还可以在krams:::: Spring Security 3: Full ACL Tutorial上找到有关 ACL 的完整教程

My advice : try and experiment and ask questions here if you get stuck on some specific problems.我的建议:如果您遇到某些特定问题,请尝试尝试并在这里提出问题。

You can use @PreRemove/ @PreUpdate / @PrePersist in your entity and implements you own logic.您可以在实体中使用 @PreRemove/@PreUpdate/@PrePersist 并实现您自己的逻辑。

  @PreRemove
    private void preventUnAuthorizedRemove() {

       String name = SecurityContextHolder.getContext().getAuthentication().getName();

      if(!name.equals(this.username)){
          throw new NotAuthorizedException("User can only delete himself ");
      }

    }

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

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