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

如下代码集成自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配置文件中设置角色名称不能带前缀,否则源码的方法会抛出非法参数异常。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值