Ich habe diesen Code in meiner Web Security-Konfiguration:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/**")
.hasRole("ADMIN")
.and()
.httpBasic().and().csrf().disable();
}
Also fügte ich einen Benutzer mit der Rolle "ADMIN" in meiner Datenbank hinzu und ich bekomme immer einen 403-Fehler, wenn ich mich mit diesem Benutzer anmeldete. Dann habe ich das Protokoll für den Frühling aktiviert und diese Zeile gefunden:
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')]
Warum sucht Spring Security "ROLE_ADMIN" statt "ADMIN"?
Spring Security fügt standardmäßig das Präfix "ROLE_" hinzu.
Wenn Sie möchten, dass dies entfernt oder geändert wird, schauen Sie sich das an
http://forum.spring.io/forum/spring-projects/security/51066-how-to-change-role-von-interceptor-url
BEARBEITEN: Auch dies gefunden: Spring Security RoleVoter-Präfix entfernen
In Spring 4 gibt es zwei Methoden, hasAuthority()
und hasAnyAuthority()
, die in der org.springframework.security.access.expression.SecurityExpressionRoot
-Klasse definiert sind. Diese beiden Methoden prüfen nur den benutzerdefinierten Rollennamen ohne Hinzufügen des ROLE_
-Präfixes. Definition wie folgt:
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;
}
Verwendungsbeispiel:
<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>
Da @olyanren traurig ist, können Sie die Methode hasAuthority () in Spring 4 anstelle von hasRole () verwenden. Ich füge ein JavaConfig-Beispiel hinzu:
@Override
protected void configure(HttpSecurity http) throws Exception {
.authorizeRequests()
.antMatchers("/api/**")
.access("hasAuthority('ADMIN')")
.and()
.httpBasic().and().csrf().disable();
}
Sie können einen Mapper erstellen, um am Anfang aller Ihrer Rollen _ROLE
hinzuzufügen:
@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;
}
Sie sollten den Mapper Ihrem Provider hinzufügen:
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
// your config ...
provider.setAuthoritiesMapper(authoritiesMapper());
return provider;
}