0

토큰 기반 인증을 구현하려는 RESTful 웹 응용 프로그램이 있습니다.RESTful 인증 확인

public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter { 

    private TokenAuthenticationService tokenAuthenticationService; 
public JWTLoginFilter(String url, AuthenticationManager authenticationManager) { 
    super(new AntPathRequestMatcher(url)); 
    setAuthenticationManager(authenticationManager); 
    tokenAuthenticationService = new TokenAuthenticationService(); 
} 

@Override 
public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) 
throws AuthenticationException, IOException, ServletException { 
    ServletInputStream inputStream = httpServletRequest.getInputStream(); 
    httpServletRequest.getCharacterEncoding(); 

    ObjectMapper mapper = new ObjectMapper(); 
    AccountCredentials credentials = mapper.readValue(inputStream, AccountCredentials.class); 

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(credentials.getUsername(), credentials.getPassword()); 
    return getAuthenticationManager().authenticate(token); 
} 
@Override 
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) 
throws IOException, ServletException { 
    String name = authentication.getName(); 
    tokenAuthenticationService.addAuthentication(response, name); 
    } 
} 

이 클래스는 요청을 차단하기 위해 JWTAuthenticationFilter을 확장해야하는 :

public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

    @Autowired 
    JpaConfiguration jpaConfiguration; 
    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     // disable caching 
     http.headers().cacheControl();   
     http.csrf().disable() // disable csrf for our requests. 
      .authorizeRequests() 
      .antMatchers("/").permitAll() 
      .antMatchers(HttpMethod.POST, "/login").permitAll() 
      .anyRequest().authenticated() 
      .and() 
      // Here the login requests is filtered 
      .addFilterBefore(new JWTLoginFilter("/login", authenticationManager()), UsernamePasswordAuthenticationFilter.class) 
      // Much probably here I have to filter other requests to check the presence of JWT in header, 
      // here i just add a commented block with teh name of the Filter 
       //.addFilterBefore(new JWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class) 
       ; 
      } 
    } 

JWTLoginFilter 클래스는 다음과 같습니다 : 다음과 같이 저는 필터 클래스와 요청을 차단 토큰을 발행 할 수 있었다 ?

여전히 AbstractAuthenticationProcessingFilter 클래스입니까?

토큰 기반 인증을 개발하는 더 좋은 방법이 있습니까?

답변

0

그래서 나는 마침내 해결책 찾기 참조 수 있습니다 예 :

public class JWTAuthenticationFilter extends GenericFilterBean implements Filter { 

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

      SecurityContextHolder.getContext().setAuthentication(token); 
      chain.doFilter(servletRequest, response); 
     }catch(Exception e){ 
      e.printStackTrace(); 
     } 
    } 
} 

JWTAuthenticationFilter이 확장하는 GenericFilterBean 클래스와 봄 보안 필터를 구현해야합니다, 메스 od doFilter가 트릭을 수행합니다.

참고 : 메서드를 FilterChain 클래스에서 호출해야합니다. 더 이상 새 클래스를 끝점으로 이동해야합니다.

0

JWTLoginFilter가 사용 된 이유를 정확히 알지 못합니다. 나는 OAuth2에 의해 안전한 RESTful을 개발하는 프로젝트에서하고있다. 개요에서 요청자는 권한 부여를 위해 REST API와 함께 액세스 토큰을 전달해야합니다.

아래는

@Configuration 
@EnableResourceServer 
public class Oauth2AuthConfiguration implements ResourceServerConfigurer { 
     @Autowired 
     private OAuth2RemoteTokenServices tokenServices; 

     @Override 
     public void configure(ResourceServerSecurityConfigurer resources) throws Exception { 
      resources.tokenServices(tokenServices); 
     } 

     @Override 
     public void configure(HttpSecurity httpSecurity) throws Exception { 
     httpSecurity.exceptionHandling() 
      .accessDeniedHandler(new PPDAccessDeniedHandler()) 
      .authenticationEntryPoint(new PPDAuthenticationEntryPoint()) 
      .and() 
     .authorizeRequests() 
      .antMatchers(POST, "/api/test").hasAuthority("PARTNER"); 
     } 
} 

OAuth2RemoteTokenServices.java

public class OAuth2RemoteTokenServices implements ResourceServerTokenServices{ 
    //implement how you can validate token here 
    // reference: org.springframework.security.oauth2.provider.token.RemoteTokenServices 
}