Milk Packet
Milk Packet
JCHJava Community | Help. Code. Learn.
Created by Milk Packet on 10/13/2024 in #java-help
How do I reduce Spring Boot's docker image size?
With my current Dockerfile configuration for a barebones spring app (straight from start.spring.io) with dependencies like web, redis, postgres, security, mail sender, etc, the size of the image is at ~350mb and I was told this was pretty large for a barebones application. Here's my dockerfile
# Build stage
FROM amazoncorretto:17-alpine AS build
WORKDIR /app

RUN apk add --no-cache maven

COPY pom.xml .
RUN mvn dependency:go-offline -B

COPY src ./src
RUN mvn package -DskipTests -B

# Runtime stage
FROM amazoncorretto:17-alpine
WORKDIR /app

COPY --from=build /app/target/tunnityserver-*.jar ./tunnityserver.jar

EXPOSE 8080

ENTRYPOINT ["java", "-jar", "tunnityserver.jar"]
# Build stage
FROM amazoncorretto:17-alpine AS build
WORKDIR /app

RUN apk add --no-cache maven

COPY pom.xml .
RUN mvn dependency:go-offline -B

COPY src ./src
RUN mvn package -DskipTests -B

# Runtime stage
FROM amazoncorretto:17-alpine
WORKDIR /app

COPY --from=build /app/target/tunnityserver-*.jar ./tunnityserver.jar

EXPOSE 8080

ENTRYPOINT ["java", "-jar", "tunnityserver.jar"]
how can I optimise it?
8 replies
JCHJava Community | Help. Code. Learn.
Created by Milk Packet on 9/15/2024 in #java-help
Spring Boot Oauth Login error
Im getting a java.lang.IllegalArgumentException: Invalid character found in the request target [/login?error=[authorization_request_not_found] ]. The valid characters are defined in RFC 7230 and RFC 3986 error when I try to login with google oauth setup on my spring backend. Here is my security config and oauthsuccess handler https://pastebin.com/raw/wKCKjxnN any help, please?
4 replies
JCHJava Community | Help. Code. Learn.
Created by Milk Packet on 9/15/2024 in #java-help
Spring Boot Google OAuth error
Im getting a java.lang.IllegalArgumentException: Invalid character found in the request target [/login?error=[authorization_request_not_found] ]. The valid characters are defined in RFC 7230 and RFC 3986 error when I try to login with google oauth setup on my spring backend. Here is my security config and oauthsuccess handler https://pastebin.com/raw/wKCKjxnN any help, please?
4 replies
JCHJava Community | Help. Code. Learn.
Created by Milk Packet on 7/22/2024 in #java-help
How do I use UserDetailsService properly? Where do I define it exactly?
I was going through spring security's docs and found this
@Configuration
@EnableWebSecurity
public class SecurityConfig {

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((authorize) -> authorize
.requestMatchers("/login").permitAll()
.anyRequest().authenticated()
);

return http.build();
}

@Bean
public AuthenticationManager authenticationManager(
UserDetailsService userDetailsService,
PasswordEncoder passwordEncoder) {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService);
authenticationProvider.setPasswordEncoder(passwordEncoder);

return new ProviderManager(authenticationProvider);
}

@Bean
public UserDetailsService userDetailsService() {
UserDetails userDetails = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();

return new InMemoryUserDetailsManager(userDetails);
}

@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}

}
@Configuration
@EnableWebSecurity
public class SecurityConfig {

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((authorize) -> authorize
.requestMatchers("/login").permitAll()
.anyRequest().authenticated()
);

return http.build();
}

@Bean
public AuthenticationManager authenticationManager(
UserDetailsService userDetailsService,
PasswordEncoder passwordEncoder) {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService);
authenticationProvider.setPasswordEncoder(passwordEncoder);

return new ProviderManager(authenticationProvider);
}

@Bean
public UserDetailsService userDetailsService() {
UserDetails userDetails = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();

return new InMemoryUserDetailsManager(userDetails);
}

@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}

}
while I know this was just an example, how do I properly define userDetailsService and where?
9 replies
JCHJava Community | Help. Code. Learn.
Created by Milk Packet on 6/15/2024 in #java-help
How to access authenticated user/authentication object on react frontend after logging in?
I've set up a basic authentication flow using Spring Security 6 on my backend, with React handling the frontend for login, signup, and verification pages. It's all session cookie-based, no JWT, with sessions stored in Redis. Now, I'm wondering how I can handle things on the React side once a user logs in. How do I check if a user is logged in to restrict access to certain pages? I want to redirect them to the login page if they're not logged in or restrict page access based on their roles. Any tips on how to manage this? I also want to be able to get access to the authenticated user's details like their email, username, etc unless this isn't possible without implementing a /me endpoint on the backend that fetches the user details for me.
45 replies
JCHJava Community | Help. Code. Learn.
Created by Milk Packet on 6/11/2024 in #java-help
Trying to implement CSRF protection with Spring Security and React frontend
I'm trying to get CSRF protection to work using spring security but I keep getting a 403 forbidden error when trying to make a post request to a csrf protected endpoint using postman. I followed the docs to the letter - this one to be specific with the only change being I replaced this line .addFilterAfter(new CsrfCookieFilter(), BasicAuthenticationFilter.class); with .addFilterAfter(new CsrfCookieFilter(), customUsernamePasswordAuthFilter.getClass()) as I have implemented a custom UsernamePasswordAuthenticationFilter to work with my frontend SPA built using react. On postman, there are two cookies present - SESSION and XSRF-TOKEN and I also include a X-XSRF-TOKEN header while making the post request and still get a forbidden error. I'm not currently sending any requests from the SPA directly. Just using postman for now.
6 replies
JCHJava Community | Help. Code. Learn.
Created by Milk Packet on 6/10/2024 in #java-help
Need help setting up CSRF on spring backend with a react frontend
I was just going through the spring docs to setup csrf protection with a SPA (react) frontend and found this code here that they suggested I use,
@Configuration
@EnableWebSecurity
public class SecurityConfig {

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
// ...
.csrf((csrf) -> csrf
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.csrfTokenRequestHandler(new SpaCsrfTokenRequestHandler())
)
.addFilterAfter(new CsrfCookieFilter(), BasicAuthenticationFilter.class);
return http.build();
}
}
@Configuration
@EnableWebSecurity
public class SecurityConfig {

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
// ...
.csrf((csrf) -> csrf
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.csrfTokenRequestHandler(new SpaCsrfTokenRequestHandler())
)
.addFilterAfter(new CsrfCookieFilter(), BasicAuthenticationFilter.class);
return http.build();
}
}
12 replies
JCHJava Community | Help. Code. Learn.
Created by Milk Packet on 6/4/2024 in #java-help
Session not being created after explicitly authenticating user in spring security
I'm currently trying to implement a session based authentication using spring security and have managed to get the registration and email verification functionality working. I want the user to be authenticated after verifying their email and then be redirected to the onboarding page and then to dashboard on completion of onboarding. I have logged the authentication to console to debug and when there isn't any user then I get a console log with the authentication object containing anonymousUser and also a sessionId. But, when I explicitly try to authenticate the user, the authentication object contains all the info about the user such as principal, etc but not sessionId. any help, please? Here is my security config.
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

http
.anonymous(t -> t.disable())
.cors(Customizer.withDefaults())
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(request -> request.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/health").permitAll()
.anyRequest().authenticated())
.formLogin(form -> form
.loginPage("/login")
.usernameParameter("email")
.failureUrl("/login?error=true")
.defaultSuccessUrl("/dashboard", true)
.permitAll())
.logout(logout -> logout
.logoutUrl("/api/auth/logout")
.logoutSuccessUrl("/login?logoutSuccess=true")
.deleteCookies("JSESSIONID")
.permitAll())
.exceptionHandling(
e -> e.authenticationEntryPoint(new AuthEntryPoint("/login")))
.sessionManagement(s -> s
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.sessionFixation().migrateSession()
.invalidSessionUrl("/login")
.sessionAuthenticationErrorUrl("/login")
.maximumSessions(10)
.maxSessionsPreventsLogin(true)
.expiredUrl("/login"));

return http.build();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

http
.anonymous(t -> t.disable())
.cors(Customizer.withDefaults())
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(request -> request.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/health").permitAll()
.anyRequest().authenticated())
.formLogin(form -> form
.loginPage("/login")
.usernameParameter("email")
.failureUrl("/login?error=true")
.defaultSuccessUrl("/dashboard", true)
.permitAll())
.logout(logout -> logout
.logoutUrl("/api/auth/logout")
.logoutSuccessUrl("/login?logoutSuccess=true")
.deleteCookies("JSESSIONID")
.permitAll())
.exceptionHandling(
e -> e.authenticationEntryPoint(new AuthEntryPoint("/login")))
.sessionManagement(s -> s
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.sessionFixation().migrateSession()
.invalidSessionUrl("/login")
.sessionAuthenticationErrorUrl("/login")
.maximumSessions(10)
.maxSessionsPreventsLogin(true)
.expiredUrl("/login"));

return http.build();
}
7 replies
JCHJava Community | Help. Code. Learn.
Created by Milk Packet on 4/26/2024 in #java-help
Custom Auth filter not being invoked in spring security
I have implement a custom authentication filter to log the user in and it's not being invoked when I try to hit the login endpoint using postman. here is the code for the CustomAuthFilter:
8 replies