【发布时间】:2019-01-13 12:42:43
【问题描述】:
什么是 Spring Security 上下文中的角色。如何定义它。我不是在问编码。 Spring Boot 中角色的一般定义是什么?有人请用适当的例子给出一个定义
【问题讨论】:
标签: spring spring-boot model-view-controller spring-security
什么是 Spring Security 上下文中的角色。如何定义它。我不是在问编码。 Spring Boot 中角色的一般定义是什么?有人请用适当的例子给出一个定义
【问题讨论】:
标签: spring spring-boot model-view-controller spring-security
我假设您正在谈论我们可以在 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_ADMIN 和ROLE_USER 访问。
您可以定义您的自定义用户角色。您需要将每个用户与角色相关联,并在 authorizeRequests 中进行配置。
您可以找到很多关于此的博客。 Here is one
【讨论】: