Spring Rest API interceptor add response header on each/every request - rest

I am working with Spring 4 REST API annotation based configuration application. I want to add response header on each/every request once user is authenticate by JWT. I have created interceptor for that which looks as below:
public class AuthenticateInterceptor implements HandlerInterceptor {
#Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception arg3)
throws Exception {
response.addHeader("afterCompletion", "afterCompletion header");
response.setHeader("afterCompletion", "afterCompletion header");
System.out.println("************** afterCompletion **************");
}
#Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object,
ModelAndView modelAndView) throws Exception {
response.addHeader("postHandle", "postHandle header");
System.out.println("************** postHandle **************");
}
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
System.out.println("************** preHandle **************");
return true;
}
}
My interceptor configuration is as below:
#Configuration
public class AdapterConfig extends WebMvcConfigurerAdapter {
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AuthenticateInterceptor());
}
}
When I get JSON response I am not able the see the added header value which are added from interceptor. Any one help me what is the issue and how can I add header from interceptor for each/every request.

I didn't succeed in interceptors, Instead using Filters or WebFilter perfectly works:
#Component
public class ResponseHeaderWebFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse.setHeader("CustomHeaderName", "SomeValue");
chain.doFilter(request, response);
}
}
In case you are using webflux reactive component, then :
#Component
public class ResponseHeaderWebFilter implements WebFilter {
#Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
exchange.getResponse()
.getHeaders()
.add("CustomHeaderName", "SomeValue");
return chain.filter(exchange);
}
}

If it can help you, I've managed it like this: https://stackoverflow.com/a/49431665/4939245
Look at second point
You can put the response header for each call in the application (this is for Spring annotation-based):
#Component
public class Filter extends OncePerRequestFilter {
....
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
//response.addHeader("Access-Control-Allow-Origin", "*");
//response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
response.setHeader("Cache-Control", "no-store"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setHeader("Expires", "0"); // Proxies.
filterChain.doFilter(request, response);
}
}
I hope I was helpful!

You are almost doing same but would like to give you consitant way of achieving same. Please do following changes.
1) Add #Component annotation on AuthenticateInterceptor class. And you package containing this class should be in packages scanned list.
#Component
public class AuthenticateInterceptor implements HandlerInterceptor {
...
}
2) Autowire and inject instance of AuthenticateInterceptor like below.
#Configuration
public class AdapterConfig extends WebMvcConfigurerAdapter {
#Autowired
private AuthenticateInterceptor authenticateInterceptor;
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authenticateInterceptor);
}
}

Related

Jersey Server Request/Response filter thread safe

I want to add some MDC logging to all my REST requests and I am using jersey. I have seen some examples of this online but I can't find any info on the thread safety of doing this:
https://coderwall.com/p/qjwyya/jax-rs-mapped-diagnostic-context-filter
#Provider
public class HttpMDCRequestListener implements ContainerRequestFilter, ContainerResponseFilter {
#Override
public void filter(ContainerRequestContext containerRequestContext) throws IOException {
MDC.put("test", "blah");
}
#Override
public void filter(ContainerRequestContext containerRequestContext,
ContainerResponseContext containerResponseContext) throws IOException {
MDC.clear();
}
Is there a new instance of this class for each request? I want to make sure I am clearing the MDC on the same thread as the request.
thanks

Spring boot api gives 403 forbidden error

I have a spring boot application with a mongo databse and spring security as a dependency.
It has two services first one for authentication and second one for application resource (entities, services controllers).
This is my config class in the authentication service:
#Configuration
#EnableWebSecurity
public class AuthServerSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
#Bean
protected UserDetailsService userDetailsService() {
return new MongoUserDetailsService();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests().anyRequest().authenticated();
System.out.println("auth");
}
#Override
public void configure(WebSecurity web) throws Exception {
super.configure(web);
}
#Bean(name="authenticationManager")
#Lazy
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
this is the rest controller:
#CrossOrigin(origins = "*", maxAge = 3600)
#RestController
#RequestMapping(value = "/api/users")
public class UserController {
#Autowired
UserServiceImpl userServiceImpl;
//Getting all users
#GetMapping(value = "")
public List<UserDTO> getAllUsers() {
return userServiceImpl.getAllUsers();
}
//Getting a user by ID
#GetMapping(value = "/profil/{userId}")
public UserDTO getUserById(#PathVariable String userId) {
return userServiceImpl.getUserById(userId);
}
//Getting a user by Username
#GetMapping(value = "/profil/username/{username}")
public UserDTO getUserByUsernameOrEmail(String username) {
return userServiceImpl.getUserByUsernameOrEmail(username);
}
//Logout user and delete token
#PostMapping("/logout")
public void logout(HttpServletRequest request) {
userServiceImpl.logout(request);
}
I changed my configure method to this :
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests() // authorize
.anyRequest().authenticated() // all requests are authenticated
.and()
.httpBasic();
http.cors();
}
Now i get 401 unauthorized when acceccing protected resources.The problem is now even when i send the correct bearer token in the request header i still get 401 unauthorized "Full authentication is required to access this resource"
Update:
I changed my project architecture from microservices to one simple spring boot project.
this is the new code of the class "AuthServerSecurityConfig"
#Configuration
public class AuthServerSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
#Bean
protected UserDetailsService userDetailsService() {
return new MongoUserDetailsService();
}
#Autowired
BCryptPasswordEncoder passwordEncoder;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//auth.userDetailsService(userDetailsService());
auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.anonymous().disable()
.authorizeRequests()
.antMatchers("/oauth/token").permitAll().and()
.httpBasic();
http.cors();
}
#Override
public void configure(WebSecurity web) throws Exception {
super.configure(web);
}
#Bean(name="authenticationManager")
#Lazy
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
and this "ResourceServerConfig" code:
#Configuration
#EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
#Autowired private ResourceServerTokenServices tokenServices;
#Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId("foo").tokenServices(tokenServices);
}
#Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests() // authorize
.antMatchers("/oauth/**").permitAll();
http
.authorizeRequests().antMatchers("/api/**").authenticated();
http
.headers().addHeaderWriter(new HeaderWriter() {
#Override
public void writeHeaders(HttpServletRequest request, HttpServletResponse response) {
response.addHeader("Access-Control-Allow-Origin", "*");
if (request.getMethod().equals("OPTIONS")) {
response.setHeader("Access-Control-Allow-Methods", request.getHeader("Access-Control-Request-Method"));
response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
}
}
});
}
}
When i try to access protected resource i get "error": "unauthorized",
"error_description": "Full authentication is required to access this resource", Which is the normal behaviour.The problem is now i can't login to get the user aceess_token.
I get "401 unauthorized" when accessing this endpoint "http://localhost:8080/oauth/token?grant_type=password&username=user&password=user".
These are the default init user credentials and the user exists in my mongodatabase with a crypted and correct format password starts with "$2a" and has "60" caracters.
I get in "Encoded password does not look like BCrypt
Authentication failed: password does not match stored value" in the console when trying to login.
In ResourceServerConfig class file, in the configure method change to the below code.
http
.csrf().disable()
.anonymous().disable()
.authorizeRequests()
.antMatchers("/oauth/token").permitAll().and()
.httpBasic();
Let me know if it worked.
Here's an example of configuration spring security with a jwt token check :
you can change the data source from h2 to mongodb and find the filters and providers used in my repo :
https://github.com/e2rabi/sbs-user-management/tree/main/sbs-user-management
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled=true)
#FieldDefaults(level = PRIVATE, makeFinal = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final RequestMatcher PUBLIC_URLS = new OrRequestMatcher(
// Put your public API here
new AntPathRequestMatcher("/public/**"),
new AntPathRequestMatcher("/h2-console/**"),
);
private static final RequestMatcher PROTECTED_URLS = new NegatedRequestMatcher(PUBLIC_URLS);
TokenAuthenticationProvider provider;
SecurityConfig(final TokenAuthenticationProvider provider) {
super();
this.provider = requireNonNull(provider);
}
#Override
protected void configure(final AuthenticationManagerBuilder auth) {
auth.authenticationProvider(provider);
}
#Override
public void configure(final WebSecurity web) {
web.ignoring().requestMatchers(PUBLIC_URLS);
}
#Override
protected void configure(final HttpSecurity http) throws Exception {
http
.sessionManagement()
.sessionCreationPolicy(STATELESS)
.and()
.exceptionHandling()
// this entry point handles when you request a protected page and you are not yet
// authenticated
.defaultAuthenticationEntryPointFor(forbiddenEntryPoint(), PROTECTED_URLS)
.and()
.authenticationProvider(provider)
.addFilterBefore(restAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.authorizeRequests()
.requestMatchers(PROTECTED_URLS)
.authenticated()
.and()
.csrf().disable()
.cors().disable()
.formLogin().disable()
.httpBasic().disable()
.logout().disable();
// h2 console config
http.headers().frameOptions().sameOrigin();
// disable page caching
http.headers().cacheControl();
}
#Bean
TokenAuthenticationFilter restAuthenticationFilter() throws Exception {
final TokenAuthenticationFilter filter = new TokenAuthenticationFilter(PROTECTED_URLS);
filter.setAuthenticationManager(authenticationManager());
filter.setAuthenticationSuccessHandler(successHandler());
return filter;
}
#Bean
SimpleUrlAuthenticationSuccessHandler successHandler() {
final SimpleUrlAuthenticationSuccessHandler successHandler = new SimpleUrlAuthenticationSuccessHandler();
successHandler.setRedirectStrategy(new NoRedirectStrategy());
return successHandler;
}
#Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
#Bean
FilterRegistrationBean disableAutoRegistration(final TokenAuthenticationFilter filter) {
final FilterRegistrationBean registration = new FilterRegistrationBean(filter);
registration.setEnabled(false);
return registration;
}
#Bean
AuthenticationEntryPoint forbiddenEntryPoint() {
return new HttpStatusEntryPoint(FORBIDDEN);
}
}
Hope that my answer can help,
you can drop a breakpoint to the line change the response status, and then check who and why it returns 403, it can finally help you get the solution
Drop a breakpoint on the line set the 403 status, to see how this happen from the stackframes.
Guess that it returns 403 without much other information, but it must need to set the status to the response, right? So drop a breakpoint to the setStatus method, I don't know where it should locate, in tomcat lib, spring lib, or servlet lib. Check the HttpResponse, they're several implementation, set the breakpoints for those setStatus/setCode methods. (Next you can see it acutally happens at HttpResponseWrapper::setStatus)
Analyze the stackframes to see what's going on there
please check https://stackoverflow.com/a/73577697/4033979

Secure Rest API Spring MVC

been trying to implement spring security to REST api but they work even without the username & password
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static String REALM="MY_TEST_REALM";
#Autowired
RestAuthenticationEntryPoint restAuthenticationEntryPoint;
#Autowired
public void ConfigureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("admin").password("admin").roles("USER", "ADMIN");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/user").hasRole("ADMIN")
.and().httpBasic().realmName(REALM).authenticationEntryPoint(gEntryPoint())
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
#Bean
public RestAuthenticationEntryPoint gEntryPoint() {
return new RestAuthenticationEntryPoint();
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(HttpMethod.OPTIONS, "/*");
}
}
Rest authetication entry point
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint{
#Override
public void commence(
HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException {
response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized" );
}
}
Rest Controller
#RestController
#RequestMapping(value = "/dray")
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class dray {
#RequestMapping(value = "/user", method = RequestMethod.GET)
#ResponseBody
public Auser getUser() {
return new Auser("john", "carter");
}
}
requests to jsp pages work fine, if user is not authenticated, he's redirected to the login form of spring security but rest api work without even asking for credentials, so how to send response 401 unauthorized if api used doesn't have the credentials?

How to trigger a CLIENT_ERROR or SERVER_ERROR with entity?

I'm trying to debug an web application running on Glassfish and I want to cause the server to return a CLIENT_ERROR or SERVER_ERROR.
The returned javax.ws.rs.core.Response to the calling server should include an entity. What is the best way to do this?
Create a filter and make it return the required Response:
javax.ws.rs.container.ContainerRequestFilter
#Provider
public class RequestFilter implements ContainerRequestFilter {
/** {#inheritDoc} */
#Override
public void filter(final ContainerRequestContext req) throws IOException {
if (req.getUriInfo().getPath().toLowerCase().contains("pathToMatch")) {
final Response newResp = Response.status(500).entity("<test>test</test>").type(MediaType.valueOf(MediaType.TEXT_HTML)).build();
req.abortWith(newResp);
}
}
}

Multiple ContainerRequestFilter for Jersey

We are planning on using Jersey's reference implementation for our REST APIs. As a prototype effort, I was also playing around with the ContainerRequestFilters and I implemented multiple of them. Is there a way in which we can control the order in which these filters are executed?
The scenario that I am thinking over here is to ensure that the security filter must be the first one to run, and if required establish the SecurityContext and then execute other filters.
Yes you can control this with the javax.annotation.Priority attribute and the default javax.ws.rs.Priorities. For example if you wanted:
Logging filter always runs first
Authentication filter should run next
Authorization filter should run next
Custom filter should always run after others
You could do:
#Priority(Integer.MIN_VALUE)
public class CustomLoggingFilter implements ContainerRequestFilter
{
#Override
public void filter(ContainerRequestContext requestContext) throws IOException
{
// DO LOGGING HERE, THIS RUNS FIRST
}
}
#Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter
{
#Override
public void filter(ContainerRequestContext requestContext) throws IOException
{
String authHeader = requestContext.getHeaderString(HttpHeaders.WWW_AUTHENTICATE);
// DO AUTHENTICATION HERE, THIS RUNS SECOND
}
}
#Priority(Priorities.AUTHORIZATION)
public class AuthorizationFilter implements ContainerRequestFilter
{
#Override
public void filter(ContainerRequestContext requestContext) throws IOException
{
String authHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
// DO AUTHORIZATION HERE, THIS RUNS THIRD
}
}
#Priority(Priorities.USER)
public class MyAwesomeStuffFilter implements ContainerRequestFilter
{
#Override
public void filter(ContainerRequestContext requestContext) throws IOException
{
// DO AWESOME STUFF HERE, THIS RUNS LAST
}
}