【问题标题】:How can I use roles in Spring?如何在 Spring 中使用角色?
【发布时间】:2019-04-12 08:32:30
【问题描述】:

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

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

【问题讨论】:

  • 你还有其他的设置吗?像您的实体、数据库、UserDetails 等?
  • 是的,我知道,目前这是唯一不清楚的部分。
  • 请看下面我的回答。告诉我这是否能消除你的歧义,否则让我知道你所有与安全相关的课程等等......

标签: java spring authorization roles


【解决方案1】:

如果您已经设置了 securityConfig 文件,那么您所需要做的就是允许不同用户角色访问不同的页面,您可以在 SecurityConfig 类中执行以下操作:

@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 Security ?如果您想使用自己的功能,例如 if user_role == A_Certain_User_Role,他们可以访问某个页面,那么为什么要使用 Spring Security 呢? Spring Security 可以让我们摆脱所有重复且耗时的样板代码。长话短说,是的,就是这么简单。
  • 谢谢,我只是想知道正确的方法。
【解决方案2】:

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

@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();
}

这是一个简短的答案。

【讨论】:

    【解决方案3】:

    首先将 Spring Security 依赖项添加到您的 pom.xml。现在使用一个类通过扩展 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();
    
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-02
      • 2020-04-25
      • 2014-05-09
      • 2018-07-14
      • 1970-01-01
      • 2010-11-02
      • 1970-01-01
      • 2011-01-31
      • 2017-09-08
      相关资源
      最近更新 更多