允许用户使用jwt在spring boot中选择资源

时间:2018-04-09 09:37:51

标签: spring authentication jwt

作为标题,我试图只让" ROLE_ADMIN"在我的应用程序上有权创建锦标赛。

我的用户:

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public long id;

private String username;

@Length(min = 2, max = 60)
private String password;

private String email;

private Long tsRegistration;

private Long tslLastLogin;

private Long bonusCredit;

private boolean enabled;

@ManyToMany
@JoinTable(name = "user_intournament", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
        inverseJoinColumns = @JoinColumn(name = "tournament_id", referencedColumnName = "id"))
public List<Tournament> tournament;

@ManyToMany
@JoinTable(
        name = "users_roles",
        joinColumns = @JoinColumn(
                name = "user_id", referencedColumnName = "id"),
        inverseJoinColumns = @JoinColumn(
                name = "role_id", referencedColumnName = "id"))
private Collection<Role> roles;



private boolean tokenExpired;

作用:

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String name;
@ManyToMany(mappedBy = "roles")
private Collection<ApplicationUser> users;

@ManyToMany
@JoinTable(
        name = "roles_privileges",
        joinColumns = @JoinColumn(
                name = "role_id", referencedColumnName = "id"),
        inverseJoinColumns = @JoinColumn(
                name = "privilege_id", referencedColumnName = "id"))
private Collection<Privilege> privileges;

和权限类:

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String name;

@ManyToMany(mappedBy = "privileges")
private Collection<Role> roles;

我创建了一个具有管理员权限的示例测试用户:

    @Override
    @Transactional
    public void onApplicationEvent(ContextRefreshedEvent event) {

        if (alreadySetup)
            return;
        Privilege readPrivilege
                = createPrivilegeIfNotFound("READ_PRIVILEGE");
        Privilege writePrivilege
                = createPrivilegeIfNotFound("WRITE_PRIVILEGE");

        List<Privilege> adminPrivileges = Arrays.asList(
                readPrivilege, writePrivilege);
        createRoleIfNotFound("ROLE_ADMIN", adminPrivileges);
        createRoleIfNotFound("ROLE_USER", Arrays.asList(readPrivilege));

        Role adminRole = roleRepository.findByName("ROLE_ADMIN");
        ApplicationUser user = new ApplicationUser();
        user.setUsername("Test");
        // user.setLastName("Test");
        user.setPassword(passwordEncoder.encode("test"));
        user.setEmail("test@test.com");
        user.setRoles(Arrays.asList(adminRole));
        user.setEnabled(true);
        userRepository.save(user);

        alreadySetup = true;

    }

之后,在我的WebSecurity上,我只允许具有admin角色的用户执行此操作。

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable().authorizeRequests()
            .antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()
            .antMatchers(HttpMethod.POST, "/tournaments").access("hasRole('ROLE_ADMIN')")
            .anyRequest().authenticated()
            .and()
            .addFilter(new JWTAuthenticationFilter(authenticationManager()))
            .addFilter(new JWTAuthorizationFilter(authenticationManager()))
            // this disables session creation on Spring Security
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

我尝试使用.hasRole("ADMIN")hasAuthority("ROLE_ADMIN"),但它不起作用,因为我收到了403禁止消息。

我设法使用&#34;测试&#34;和&#34;测试&#34;通过邮递员获取凭证并检索持票人令牌,这使我可以访问需要身份验证的所有资源,但需要管理员角色的资源除外。

1 个答案:

答案 0 :(得分:0)

你可以试试这个

吗?
.antMatchers(HttpMethod.POST, "/tournaments/**").access("hasRole('ROLE_ADMIN')")