001/*
002 * Licensed under the Apache License, Version 2.0 (the "License");
003 * you may not use this file except in compliance with the License.
004 * You may obtain a copy of the License at
005 *
006 *     http://www.apache.org/licenses/LICENSE-2.0
007 *
008 * Unless required by applicable law or agreed to in writing, software
009 * distributed under the License is distributed on an "AS IS" BASIS,
010 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
011 * See the License for the specific language governing permissions and
012 * limitations under the License.
013 */
014package org.gbif.ws.security;
015
016import org.springframework.context.annotation.Configuration;
017import org.springframework.security.access.AccessDecisionManager;
018import org.springframework.security.access.vote.AffirmativeBased;
019import org.springframework.security.access.vote.RoleVoter;
020import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
021import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
022
023@Configuration
024@EnableGlobalMethodSecurity(securedEnabled = true, jsr250Enabled = true, prePostEnabled = true)
025public class RoleMethodSecurityConfiguration extends GlobalMethodSecurityConfiguration {
026
027  @Override
028  protected AccessDecisionManager accessDecisionManager() {
029    AffirmativeBased accessDecisionManager = (AffirmativeBased) super.accessDecisionManager();
030
031    // Remove the ROLE_ prefix from RoleVoter for @Secured and hasRole checks on methods
032    accessDecisionManager.getDecisionVoters().stream()
033        .filter(RoleVoter.class::isInstance)
034        .map(RoleVoter.class::cast)
035        .forEach(it -> it.setRolePrefix(""));
036
037    return accessDecisionManager;
038  }
039}