如何使用 Spring 中的角色?

How can I use roles in Spring?

在我的应用程序中,我有以下角色: 来宾、用户、所有者和管理员

我想使用某种授权,管理员可以使用所有端点,而所有者可以使用用户拥有的所有功能。我应该如何实现这一目标?什么是好的做法?

您可以使用安全方法。首先,你需要启用方法安全,你可以这样做:

@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true) //THIS IS THE KEY
public class SecurityConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
    }
}

启用后,您可以方便地按方法和用户使用安全性,例如:

@GetMapping("/ativas")
@PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_USER') and #oauth2.hasScope('read')")
public List<YourObject> findAll(){
    return service.findAll();
}

这是一个简短的回答。

如果您设置了 securityConfig 文件,那么您需要做的就是允许不同的用户角色访问不同的页面,您可以按照 SecurityConfig class 中的以下方式进行操作:

@Override
    protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests()
        .antMatchers("/homePage").access("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")
        .antMatchers("/userPage").access("hasRole('ROLE_USER')")
        .antMatchers("/adminPage").access("hasRole('ROLE_ADMIN')")
        .and()
            .formLogin().loginPage("/loginPage")
            .defaultSuccessUrl("/homePage")
            .failureUrl("/loginPage?error")
            .usernameParameter("username").passwordParameter("password")                
        .and()
            .logout().logoutSuccessUrl("/loginPage?logout"); 

}
}

如您所见,任何具有 ROLE_ADMIN 或普通用户 (USER_ROLE) 角色的用户都可以访问主页... 如果您看到 adminPage 只能由具有 ROLE_ADMIN 角色的用户访问...

首先将 Spring 安全依赖项添加到您的 pom.xml。现在使用 class 通过扩展 webSecurityConfigurerAdapter 配置 Spring 安全。确保添加 @Configuration 和 @EnableWebSecurity 注释。看看下面的代码。这应该有所帮助。

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().withUser(id).password("{noop}" + pwd).roles("USER").and().withUser(admin_id).password("{noop}" + admin_pwd).roles("ADMIN", "USER");
}


@Override
protected void configure(HttpSecurity http) throws Exception {

    http.
    csrf().disable().authorizeRequests().antMatchers("/**").hasRole("ADMIN").
            and().httpBasic();

}