1

I am using jersey , spring boot and spring security to create rest web service. Which will be consumed by angular 2 client.

Client is sending authorization header in request , But on server i am not receiving any header value. I am using jersey for web service resource also using spring security authentication and authorization.

Kindly help.

public class SecurityConfiguration extends WebSecurityConfigurerAdapter{

@Autowired
private CustomUserDetailsService userDetailService; 

public SecurityConfiguration(CustomUserDetailsService userDetailService) {
     this.userDetailService  = userDetailService;
}

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/assets/**")
    .and().ignoring().antMatchers("/app/**")
    .and().ignoring().antMatchers("/opas/Payment/**") ;
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http.cors();
    http.authorizeRequests()
            .antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()
            .antMatchers(HttpMethod.POST, "/login").permitAll()
            .and().authorizeRequests().antMatchers("/opas/common/**").permitAll()
            .and().authorizeRequests().antMatchers("/opas/register/**").permitAll()
            .anyRequest().authenticated()                             
            .and()
            .addFilterBefore(new CORSFilter(), ChannelProcessingFilter.class)
            .addFilter(new JWTAuthenticationFilter(authenticationManager()))
            .addFilter(new JWTAuthorizationFilter(authenticationManager()))
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);


}

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailService);
}

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    final CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(ImmutableList.of("*"));
    configuration.setAllowedMethods(ImmutableList.of("HEAD","GET", "POST", "PUT", "DELETE", "PATCH","OPTIONS"));
    // setAllowCredentials(true) is important, otherwise:
    // The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
    configuration.setAllowCredentials(true);
    // setAllowedHeaders is important! Without it, OPTIONS preflight request
    // will fail with 403 Invalid CORS request
    configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type","X-Requested-With"));
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

}

I am getting null header value in following code

public class JWTAuthorizationFilter extends BasicAuthenticationFilter { 

public JWTAuthorizationFilter(AuthenticationManager authManager) {
    super(authManager);
}

@Override
protected void doFilterInternal(HttpServletRequest req,
                                HttpServletResponse res,
                                FilterChain chain) throws IOException, ServletException {
    String header = req.getHeader(HEADER_STRING);

    if (header == null || !header.startsWith(TOKEN_PREFIX)) {
        chain.doFilter(req, res);
        return;
    }    

    try {
        UsernamePasswordAuthenticationToken authentication = getAuthentication(req);
        SecurityContextHolder.getContext().setAuthentication(authentication);       
        chain.doFilter(req, res);
    }
    catch (ExpiredJwtException eje) {
        // TODO: handle exception
        ResponseMessage responseMessage = new ResponseMessage();
        responseMessage.setStatusCode(DomainConstants.FORBIDDEN_ERROR);
        responseMessage.setMessage(DomainConstants.SESSION_EXPIRED);
        Gson gson = new Gson();
        res.getWriter().write(gson.toJson(responseMessage));
    }        
}

private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request)throws ExpiredJwtException {
    String token = request.getHeader(HEADER_STRING);

        if (token != null) {
            // parse the token.
            String user = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                    .getBody()
                    .getSubject();
            if (user != null) {              
                return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>());                  
            }
            return null;
        }        
    return null;
}}

1 Answers1

0

in latest versions of spring, if your header value equal to null, you get NullPointerException in spring security. maybe for your case you need to remove it with HttpServletResponseWrapper like this post

Amir Azizkhani
  • 1,662
  • 17
  • 30