您的位置:首页 > 编程语言 > Java开发

spring security 采用角色控制访问权限

2016-09-12 23:42 155 查看
如下代码集成自spring security登陆验证方法
@Service
public class LoginUserDetailsService implements UserDetailsService {

@Override
public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {

//角色的权限组合
List<GrantedAuthority> roles = new ArrayList<GrantedAuthority>();
roles.add(new SimpleGrantedAuthority("<span style="color:#3366FF;">ROLE_COMMOM</span>"));//将权限加入组合 <span style="color:#CC0000;">此处注意角色名称必须带前缀 ROLE_</span> 原因下面叙述

User user = new User(account,tempUser.getPassword(),roles);
return user;

}

}

下面是security config的部分配置代码:

@Override
protected void configure(HttpSecurity http) throws Exception{
<pre name="code" class="java"> //设置必须有COMMOM角色的才能访问该链接  http.authorizeRequests().antMatchers("/user/welcome").hasRole("COMMOM")//注意此处角色名称不能带前缀 .anyRequest().permitAll()//所有其他请求无需认证


如下是spring security验证角色的部分源码,该方法返回securityconfig文件设置的角色名称

public final class ExpressionUrlAuthorizationConfigurer<H extends HttpSecurityBuilder<H>>
extends AbstractInterceptUrlConfigurer<ExpressionUrlAuthorizationConfigurer<H>, H> {
private static String hasRole(String role) {
Assert.notNull(role, "role cannot be null");
if (role.startsWith("ROLE_")) {
throw new IllegalArgumentException(
"role should not start with 'ROLE_' since it is automatically inserted. Got '"
+ role + "'");
}
return "hasRole('<span style="color:#3366FF;">ROLE_" + role + "</span>')";<span style="color:#FF0000;">//看,这个方法的在返回角色名称role时,自动为他添加了ROLE_前缀</span>
}综上所述,我们可以发现,我们在securityconfig配置文件配置角色名称(不带前缀),在给系统提供用户角色信息时,需要给角色加上ROLE_前缀
否则,会出现用户拥有对应角色,却依然无法访问对应路径。

ps.另外有源码我们可以发现,在securityconfig配置文件中设置角色名称不能带前缀,否则源码的方法会抛出非法参数异常。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: