2017-12-12 10 views
-1

나는 토큰을 인출 한 후 나는 다음 springsecuritycontext에 필터하는 것은 다음과 같이 덧붙였다봄 보안

@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); 
    } 
} 

토큰 관련 역할과 인증 개체를 채우는 사용자 정의 필터를 생성 :

@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(); 
    } 
} 

응용 프로그램이 이미 존재하며 스프링 보안 계층을 추가하려고합니다. 스프링 보안 버전은 4.2.3입니다. 이것을 구현하려고 시도한 후에 TokenAuthenticationFilter이로드되지 않아 요청이 필터링되지 않습니다. 도와주세요. 응용 프로그램이 이미 봄 보안 계층을 추가하기 전에 존재하기 때문에

+0

의 사용 가능한 복제 [봄 보안 토큰 기반 인증 (https://stackoverflow.com/questions/42354138/spring-security-token-based-authentication) –

답변

0

, 나는 아래의 방법으로 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>