使用自定义过滤器进行Spring安全性

时间:2017-12-12 01:38:52

标签: java spring spring-mvc spring-security

我创建了一个自定义过滤器,用于获取令牌,然后使用与令牌相关的角色填充身份验证对象

@Component
public class TokenAuthenticationFilter extends GenericFilterBean {
    @Autowired
    private IAMUserDAO iamUserDAO;
    @Autowired
    CDBUserProfileDao cdbUserProfileDao;
    @Autowired
    IAMOAuth2Dao iamOAuth2DAO;

    final static Logger logger = Logger.getLogger(TokenAuthenticationFilter.class.getCanonicalName());

    @Override
    public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
            throws IOException, ServletException {

        final HttpServletRequest httpRequest = (HttpServletRequest) request;
        final String accessToken = httpRequest.getHeader("Authorization");
        logger.info("Request with token " + accessToken + " intercepted for rba purpose");

        if (!StringUtil.isBlank(accessToken)) {
            ResponseEntity<String> tokenResponse = Utils.validateAccessToken(httpRequest, iamOAuth2DAO);
            if (tokenResponse.getStatusCode().equals(HttpStatus.OK)) {
                try {
                    UserProfiles userProfileResponse = cdbUserProfileDao.getCDBUserProfile(tokenResponse.getBody());
                    if (userProfileResponse != null) {
                        String action = iamUserDAO.getFbiFederatedAction(userProfileResponse.getEntid(),
                                userProfileResponse.getRoles().getRole());
                        if (!StringUtil.isBlank(action)) {
                            List<GrantedAuthority> authorities = Arrays.asList(action.split(",")).stream()
                                    .map(s -> new SimpleGrantedAuthority(s)).collect(Collectors.toList());
                            final User user = new User("", "", true, true, true, true, authorities);
                            final UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                                    user, null, user.getAuthorities());
                            SecurityContextHolder.getContext().setAuthentication(authentication);
                        }
                    }
                } catch (Exception e) {
                    logger.error("rba processing encounter an error " + e.getMessage());
                }
            }
        }
        logger.info("Exiting rba filter with token " + accessToken);
        chain.doFilter(request, response);
    }
}

然后我将过滤器添加到springsecuritycontext中,如下所示:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(new TokenAuthenticationFilter());
        registrationBean.setEnabled(false);
        return registrationBean;
    }

    @Override
    protected void configure(final HttpSecurity http) throws Exception {

        // Implementing Token based authentication in this filter
        http.addFilterBefore(new TokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

        http.authorizeRequests().antMatchers("/calendar/search", "/calendar/v2/search")
                .access("hasRole('use-calendar') or hasRole('admin')").anyRequest().authenticated();
    }
}

应用程序已经存在,我只是尝试添加spring安全层。弹簧安全版本是4.2.3。在尝试实现此操作数天之后,未加载TokenAuthenticationFilter,因此不会过滤任何请求。请帮忙。

1 个答案:

答案 0 :(得分:0)

由于应用程序在添加Spring Security层之前已经存在,我必须以下面的方式在web.xml文件中添加过滤器:

     <filter>
        <filter-name>tokenAuthenticationFilter</filter-name>
        <filter-class>com.mycompany.authenticateb.config.TokenAuthenticationFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>tokenAuthenticationFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>