2017-10-23 17 views
1

私はJWTを使用してアプリケーションを保護するためにthis auth0's tutorialに従っています。SpringセキュリティでカスタムログインURLを設定するUsernamePasswordAuthenticationFilter JWT認証

@EnableWebSecurity 
@AllArgsConstructor(onConstructor = @__(@Autowired)) 
public class WebSecurity extends WebSecurityConfigurerAdapter { 

    private final UserDetailsService userDetailsService; 
    private final BCryptPasswordEncoder passwordEncoder; 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http.formLogin() 
       .and().cors() 
       .and().csrf() 
       .disable() 
       .authorizeRequests() 
       .antMatchers(HttpMethod.POST, REGISTER_URL).permitAll() 
       .antMatchers(HttpMethod.POST, LOGIN_URL).permitAll() 
       .anyRequest().authenticated() 
       .and() 
       .addFilter(new JWTAuthorizationFilter(authenticationManager())) 
       .addFilter(new JWTAuthenticationFilter(authenticationManager())) 
       // This disables session creation on Spring Security 
       .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); 
    } 

    @Override 
    protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
     auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder); 
    } 

    @Bean 
    public CorsConfigurationSource corsConfigurationSource() { 
     final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 
     source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues()); 
     return source; 
    } 

} 

と、次のJWTAuthenticationFilter:私は、次のWebSecurity社構成になってしまってきた

瞬間

public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter { 

    private final AuthenticationManager authenticationManager; 

    public JWTAuthenticationFilter(AuthenticationManager authenticationManager) { 
     this.authenticationManager = authenticationManager; 
    } 

    @Override 
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { 
     try { 
      ApplicationUser credentials = new ObjectMapper().readValue(request.getInputStream(), ApplicationUser.class); 
      return authenticationManager.authenticate(
        new UsernamePasswordAuthenticationToken(
          credentials.getUsername(), 
          credentials.getPassword(), 
          new ArrayList<>() 
        ) 
      ); 
     } catch (IOException e) { 
      throw new RuntimeException(e); 
     } 
    } 

    @Override 
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { 
     String token = Jwts.builder() 
       .setSubject(((User) authResult.getPrincipal()).getUsername()) 
       .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME)) 
       .signWith(SignatureAlgorithm.HS512, SECRET.getBytes()) 
       .compact(); 
     response.addHeader(HEADER_STRING, TOKEN_PREFIX + token); 
    } 
} 

、アプリは "/ログイン" URLにPOSTリクエストを受け付け。 URLを "/ api/auth/login"に変更する方法は不思議です。認証文字列にURL文字列を挿入する方法や、セキュリティ設定で何とか設定する方法はありますか?

答えて

4

org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilterを拡張しており、それ自体が org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilterに拡張されています。

は、URLを設定します

setFilterProcessesUrl

ます。public void setFilterProcessesUrl(文字列filterProcessesUrl):この最後のクラスでは、セッターだけでこれを行うことを意図しているsetFilterProcessesUrlと呼ばれています認証が必要かどうかを決定する。

パラメータ:filterProcess

@Bean 
public JWTAuthenticationFilter getJWTAuthenticationFilter() { 
    final JWTAuthenticationFilter filter = new JWTAuthenticationFilter(authenticationManager()); 
    filter.setFilterProcessesUrl("/api/auth/login"); 
    return filter; 
} 

そして、同じクラスでのごconfigure方法でそれを参照します。esUrl

Thisは、だからあなたWebSecurityConfigurerAdapterであなたはこのように行うことができ、そのjavadocのセクション

へのリンクです新しいインスタンスを作成する代わりに:

.addFilter(getJWTAuthenticationFilter()) 
+0

ありがとう、それは魅力として働いた!あなたの答えには少し見落としがありますが、あなたはJWTAuthorizationFilterとJWTAuthenticationFilterを混同しています。しかし、それでも、それは完全に動作します。 –

+0

おっと!あなたはライトです...私はちょうどそれを修正しました。ヒントをありがとう... – jlumietu

関連する問題