【问题标题】:What is Roles in spring bootSpring Boot 中的角色是什么
【发布时间】:2019-01-13 12:42:43
【问题描述】:

什么是 Spring Security 上下文中的角色。如何定义它。我不是在问编码。 Spring Boot 中角色的一般定义是什么?有人请用适当的例子给出一个定义

【问题讨论】:

    标签: spring spring-boot model-view-controller spring-security


    【解决方案1】:

    我假设您正在谈论我们可以在 Spring Security 中提供的角色。

    如果是这样,那么您的问题应该是 Spring Security 中的角色。

    角色基本上是您授予用户的访问权限级别。

    • 可能存在只允许少数用户写入数据而其他用户只能读取信息的情况。
    • 在某些情况下,某些资源只能由一组特殊的用户访问。

    在上述所有情况下,角色扮演着重要的角色。

    让我们看看这段代码

    @Configuration
    @EnableWebSecurity
    public class LoginSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder authenticationMgr) throws Exception {
            authenticationMgr.inMemoryAuthentication()
                .withUser("jduser").password("jdu@123").authorities("ROLE_USER")
                .and()
                .withUser("jdadmin").password("jda@123").authorities("ROLE_USER","ROLE_ADMIN");
        }
    
        @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"); 
    
        }
    }
    

    您已经以某种方式配置您的应用程序

    /adminPage 只能由拥有ROLE_ADMIN 的用户使用

    /userPage, /homePage 可供ROLE_ADMINROLE_USER 访问。

    您可以定义您的自定义用户角色。您需要将每个用户与角色相关联,并在 authorizeRequests 中进行配置。

    您可以找到很多关于此的博客。 Here is one

    【讨论】:

      猜你喜欢
      • 2014-12-26
      • 2018-09-20
      • 2010-11-07
      • 1970-01-01
      • 2021-08-02
      • 1970-01-01
      • 1970-01-01
      • 2021-08-18
      • 2022-01-02
      相关资源
      最近更新 更多