I have an API which needs to be secured in two different ways:
1) Using JWT for all request URL's other than 1 which needs to be secured with Basic Auth
2) Basic Auth for one url.
I have setup security configurations for both JWT and Basic Auth. My problem is that when I make a request to the Basic Authenticated URL using a valid username and password, It successfully authenticates me and does it's job of storing data within in cassandra.
I then expect to have to generate a token for ALL other request URL's via /api/login and add it to the Authorization: Bearer {Token} header..
However, if ive been authenticated via Basic Auth, I can then access the other URL's (protected by JWT auth) without even having a token in the request.
When I access the JWT protected URL's without authenticating with Basic Auth, I have to send the token in the header and it works as expected..
Should I expect this? As I believe even though ive authenticated via basic auth for one endpoint, I should still have to send tokens in the request for all other protected JWT endpoints..
I have found this answer: SpringBoot multiple authentication adapter
and also this article: https://docs.spring.io/spring-security/site/docs/4.2.x/reference/htmlsingle/#multiple-httpsecurity
and tried implementing the solutions, but the problem as explained still occurs.
The security config class is as follows:
@Configuration
@EnableWebSecurity
public class SecurityHttpConfig extends WebSecurityConfigurerAdapter {
@Configuration
@Order(1)
public static class BasicAuthSecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${basic.auth.user}")
private String basicAuthUsername;
@Value("${basic.auth.password}")
private String basicAuthPassword;
@Value("${crashboxx.consume.endpoint}")
private String crashBoxxConsumeEndpoint;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers("/v1/crash/consumeCrashBoxxEvent").hasRole("ADMIN").and()
.httpBasic().authenticationEntryPoint(getBasicAuthEntryPoint()).and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);// We don't need sessions to be created.
}
@Bean
public CustomBasicAuthenticationEntryPoint getBasicAuthEntryPoint() {
return new CustomBasicAuthenticationEntryPoint();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
auth.inMemoryAuthentication().withUser(basicAuthUsername).password(encoder.encode(basicAuthPassword))
.roles("ADMIN");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
@Configuration
@Order(2)
public static class JwtWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
@Autowired
private JwtAuthenticationProvider jwtAuthenticationProvider;
// Any endpoints that require no authorization should be added here..
@Value("${api.login.endpoint}")
private String loginEndpoint;
@Autowired
public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) {
authenticationManagerBuilder.authenticationProvider(jwtAuthenticationProvider);
}
@Bean
public JwtAuthenticationTokenFilter authenticationTokenFilterBean() {
return new JwtAuthenticationTokenFilter();
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable().exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests().antMatchers("/api/login").permitAll().anyRequest().authenticated();
httpSecurity.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
httpSecurity.headers().cacheControl();
}
}
With the BasicAuthEntryPoint class:
public class CustomBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
private static final Gson gson = new Gson();
@Override
public void commence(final HttpServletRequest request, final HttpServletResponse response,
final AuthenticationException authException) throws IOException, ServletException {
// Authentication failed, send error response.
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
PrintWriter writer = response.getWriter();
writer.println(gson.toJson("HTTP Status 401 : " + authException.getMessage()));
}
@Override
public void afterPropertiesSet() throws Exception {
setRealmName("Realm");
super.afterPropertiesSet();
}
Also the JWT impl:
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
@Value("${jwt.header}")
private String tokenHeader;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
final String requestHeader = request.getHeader(tokenHeader);
// Ensure Auth Header contains 'Bearer'
if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
String authToken = requestHeader.substring(7);
JwtAuthentication authentication = new JwtAuthentication(authToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
chain.doFilter(request, response);
}
I hope this has made sense.. If there are any more questions please let me know, but cant seem to get round this one.
I have added the 'special case' first which is the one url for basic auth, but still does not make any differences.
Thanks
/v1/crash/**
? – PraveenKumar Lalasangi