Spring安全性为所有角色名称添加了前缀"ROLE_"?

Gus*_*lin 23 java spring spring-mvc spring-security role

我在Web Security Config中有这个代码:

 @Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers("/api/**")
            .hasRole("ADMIN")
            .and()
            .httpBasic().and().csrf().disable();

}
Run Code Online (Sandbox Code Playgroud)

所以我在我的数据库中添加了一个具有"ADMIN"角色的用户,当我尝试使用此用户登录时,我总是得到403错误,然后我启用了spring for log,我找到了这一行:

2015-10-18 23:13:24.112 DEBUG 4899 --- [nio-8080-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /api/user/login; Attributes: [hasRole('ROLE_ADMIN')]
Run Code Online (Sandbox Code Playgroud)

为什么Spring Security正在寻找"ROLE_ADMIN"而不是"ADMIN"?

jmc*_*mcg 19

Spring安全性默认添加前缀" ROLE_ ".

如果您想删除或更改此内容,请查看

http://forum.spring.io/forum/spring-projects/security/51066-how-to-change-role-from-interceptor-url

编辑:发现这一点: Spring Security删除RoleVoter前缀


oly*_*ren 16

在Spring 4中,有两种方法hasAuthority()hasAnyAuthority()org.springframework.security.access.expression.SecurityExpressionRoot类中定义.这两种方法仅检查您的自定义角色名称而不添加ROLE_前缀.定义如下:

public final boolean hasAuthority(String authority) {
    return hasAnyAuthority(authority);
}
public final boolean hasAnyAuthority(String... authorities) {
    return hasAnyAuthorityName(null, authorities);
}
private boolean hasAnyAuthorityName(String prefix, String... roles) {
    Set<String> roleSet = getAuthoritySet();

    for (String role : roles) {
        String defaultedRole = getRoleWithDefaultPrefix(prefix, role);
        if (roleSet.contains(defaultedRole)) {
            return true;
        }
    }

    return false;
}
private static String getRoleWithDefaultPrefix(String defaultRolePrefix, String role) {
    if (role == null) {
        return role;
    }
    if (defaultRolePrefix == null || defaultRolePrefix.length() == 0) {
        return role;
    }
    if (role.startsWith(defaultRolePrefix)) {
        return role;
    }
    return defaultRolePrefix + role;
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

<http auto-config="false" use-expressions="true" pattern="/user/**"
      entry-point-ref="loginUrlAuthenticationEntryPoint">
    <!--If we use hasAnyAuthority, we can remove ROLE_ prefix-->
    <intercept-url pattern="/user/home/yoneticiler" access="hasAnyAuthority('FULL_ADMIN','ADMIN')"/>
    <intercept-url pattern="/user/home/addUser" access="hasAnyAuthority('FULL_ADMIN','ADMIN')"/>
    <intercept-url pattern="/user/home/addUserGroup" access="hasAuthority('FULL_ADMIN')"/>
    <intercept-url pattern="/user/home/deleteUserGroup" access="hasAuthority('FULL_ADMIN')"/>
    <intercept-url pattern="/user/home/**" access="hasAnyAuthority('FULL_ADMIN','ADMIN','EDITOR','NORMAL')"/>
    <access-denied-handler error-page="/403"/>
    <custom-filter position="FORM_LOGIN_FILTER" ref="customUsernamePasswordAuthenticationFilter"/>
    <logout logout-url="/user/logout"
            invalidate-session="true"
            logout-success-url="/user/index?logout"/>
    <!-- enable csrf protection -->
    <csrf/>
</http>   <beans:bean id="loginUrlAuthenticationEntryPoint"
            class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
    <beans:constructor-arg value="/user"/>
</beans:bean>
Run Code Online (Sandbox Code Playgroud)


小智 9

正如@olyanren 难过的那样,您可以在 Spring 4 中使用 hasAuthority() 方法而不是 hasRole()。我正在添加 JavaConfig 示例:

@Override
protected void configure(HttpSecurity http) throws Exception {
    .authorizeRequests()
    .antMatchers("/api/**")
    .access("hasAuthority('ADMIN')")
    .and()
    .httpBasic().and().csrf().disable();
}
Run Code Online (Sandbox Code Playgroud)


Ham*_*eji 5

您可以创建一个映射器以添加ROLE_到所有角色的开头:

@Bean
public GrantedAuthoritiesMapper authoritiesMapper() {
    SimpleAuthorityMapper mapper = new SimpleAuthorityMapper();
    mapper.setPrefix("ROLE_"); // this line is not required 
    mapper.setConvertToUpperCase(true); // convert your roles to uppercase
    mapper.setDefaultAuthority("USER"); // set a default role

    return mapper;
}
Run Code Online (Sandbox Code Playgroud)

您应该将映射器添加到您的提供程序:

@Bean
public DaoAuthenticationProvider authenticationProvider() {
    DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
    // your config ...
    provider.setAuthoritiesMapper(authoritiesMapper());

    return provider;
}
Run Code Online (Sandbox Code Playgroud)