Access Denied

Hello, i have been trying to fix this alone for around a day now and i'm giving up. I'm trying to get a user id with uuid in the postman but im getting access denied and i have also debugged it. UserService
public User findUserById(UUID id) {
return userRepository.findUserById(id);
}
}
public User findUserById(UUID id) {
return userRepository.findUserById(id);
}
}
UserRepository
public interface UserRepository extends JpaRepository<User, UUID> {

Optional<User> findByEmail(String email);

boolean existsByFirstname (String firstname);
boolean existsByEmail(String email);

List<User> findAllBy();
User findUserById(UUID id);


}
public interface UserRepository extends JpaRepository<User, UUID> {

Optional<User> findByEmail(String email);

boolean existsByFirstname (String firstname);
boolean existsByEmail(String email);

List<User> findAllBy();
User findUserById(UUID id);


}
AuthenticationController
@GetMapping("user/{id}")
public User findUserByid(@PathVariable UUID id) {
return userService.findUserById(id);
}
}
@GetMapping("user/{id}")
public User findUserByid(@PathVariable UUID id) {
return userService.findUserById(id);
}
}
the debug says
Securing GET /api/v1/auth/user/cd6dc7ec-2396-4852-9e35-72a0c5196dec
Securing GET /api/v1/auth/user/cd6dc7ec-2396-4852-9e35-72a0c5196dec
Set SecurityContextHolder to anonymous SecurityContext
Set SecurityContextHolder to anonymous SecurityContext
523 Replies
JavaBot
JavaBot13mo ago
This post has been reserved for your question.
Hey @Itsurran! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
Itsurran
ItsurranOP13mo ago
When i register i get a uuid for the user and i can also login and im getting my user token, i can also logout just incase if this helps with the question.
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
package com.Nem.demo.config;

import jakarta.servlet.Filter;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutHandler;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfiguration {

private final JwtAuthenticationFilter jwtAuthFilter;

private final AuthenticationProvider authenticationProvider;

private final LogoutHandler logoutHandler;


@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.authorizeHttpRequests()
.requestMatchers("/api/v1/auth/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authenticationProvider(authenticationProvider)
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
.logout()
.logoutUrl("/api/v1/auth/logout")
.addLogoutHandler(logoutHandler)
.logoutSuccessHandler((request, response, authentication) -> SecurityContextHolder.clearContext()
);
return http.build();
}
}
package com.Nem.demo.config;

import jakarta.servlet.Filter;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutHandler;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfiguration {

private final JwtAuthenticationFilter jwtAuthFilter;

private final AuthenticationProvider authenticationProvider;

private final LogoutHandler logoutHandler;


@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.authorizeHttpRequests()
.requestMatchers("/api/v1/auth/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authenticationProvider(authenticationProvider)
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
.logout()
.logoutUrl("/api/v1/auth/logout")
.addLogoutHandler(logoutHandler)
.logoutSuccessHandler((request, response, authentication) -> SecurityContextHolder.clearContext()
);
return http.build();
}
}
Thanks for a fast response
JavaBot
JavaBot13mo ago
If you are finished with your post, please close it. If you are not, please ignore this message. Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.
Itsurran
ItsurranOP13mo ago
Before i changed i had Integer Id but i wanted UUID instead then i keep getting acess denied and i worked getting the id in the postman
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
When i had the id as integer it worked but i changed to UUID and now not workng
Itsurran
ItsurranOP13mo ago
Tell me what you need to see in the files i will show you 😄
No description
Itsurran
ItsurranOP13mo ago
Im giving up 😂
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
@RequestMapping("/api/v1/auth") yh @RequestMapping("/api/v1/auth/user/uuid") right? when im sending to postman I can screenshare if u need maybe its easier to understand
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
so a test endpoint?
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
should i just change my requestmatchers to .requestMatchers("/api/v1/auth/user/{id}") ? in securityconfig will that work or should i just add @preauthorize or soemthing in my controller
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
No description
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
Says shoul change to .equals
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
ok gonna restart
Itsurran
ItsurranOP13mo ago
No description
No description
Itsurran
ItsurranOP13mo ago
no print
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
yes
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
the debug
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
yh Want me to make the uuid to integer?
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
wtf is going on 😂 I have faith that you will help me with this idk why
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
im not autenticated rn so u know it wont let me register a user gives me 403
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
because we have it authenticated
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
yh
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
ok gonna restart and try again i get access denied when i register canged it to ** and now i can register 200 change
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
ok
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
403
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
The whole one ?
package com.Nem.demo.auth;

import com.Nem.demo.user.User;
import com.Nem.demo.user.UserRepository;
import com.Nem.demo.user.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/v1/auth")
@RequiredArgsConstructor
public class AuthenticationController {


@Autowired
private final AuthenticationService service;

@Autowired
private final UserRepository userRepository;

@Autowired
private final UserService userService;

@PostMapping("/register")
public ResponseEntity<AuthenticationResponse> register(
@RequestBody RegisterRequest request
) {

if (userRepository.existsByFirstname(request.getFirstname())) {
return ResponseEntity.badRequest().body(new AuthenticationResponse("Username is already in use"));
}
if (userRepository.existsByEmail(request.getEmail())) {
return ResponseEntity.badRequest().body(new AuthenticationResponse("Email is already in use"));
}


return ResponseEntity.ok(service.register(request));
}

@PostMapping("/authenticate")
public ResponseEntity<AuthenticationResponse> authenticate(
@RequestBody AuthenticationRequest request
) {
return ResponseEntity.ok(service.authenticate(request));
}
@GetMapping("/test")
void test(){
System.out.println("sdssdf");
}
@GetMapping("user/{id}")
public User findUserByid(@PathVariable UUID id) {
return userService.findUserById(id);
}


}
package com.Nem.demo.auth;

import com.Nem.demo.user.User;
import com.Nem.demo.user.UserRepository;
import com.Nem.demo.user.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/v1/auth")
@RequiredArgsConstructor
public class AuthenticationController {


@Autowired
private final AuthenticationService service;

@Autowired
private final UserRepository userRepository;

@Autowired
private final UserService userService;

@PostMapping("/register")
public ResponseEntity<AuthenticationResponse> register(
@RequestBody RegisterRequest request
) {

if (userRepository.existsByFirstname(request.getFirstname())) {
return ResponseEntity.badRequest().body(new AuthenticationResponse("Username is already in use"));
}
if (userRepository.existsByEmail(request.getEmail())) {
return ResponseEntity.badRequest().body(new AuthenticationResponse("Email is already in use"));
}


return ResponseEntity.ok(service.register(request));
}

@PostMapping("/authenticate")
public ResponseEntity<AuthenticationResponse> authenticate(
@RequestBody AuthenticationRequest request
) {
return ResponseEntity.ok(service.authenticate(request));
}
@GetMapping("/test")
void test(){
System.out.println("sdssdf");
}
@GetMapping("user/{id}")
public User findUserByid(@PathVariable UUID id) {
return userService.findUserById(id);
}


}
wait wait i hav e user oh my gofd in my post man i have user/test i should only be test yh 200
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
got it printed
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
nope im getting 403
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
both register and login
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
i regsiter, i get a jwt token and when i login i get another jwt token So i have a jwtService where it gerenates a token etc then i have a filter where it checks if its valid with the user
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
si i should take away the api/v1/auth? or with that
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
like dis?
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
403
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
200 ok with this i have a user
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
200 ok with login
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
so this?
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
403
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
:/
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
and comment out permitall?
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
.its good
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
ok gonna try so i login what should i do now
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
i restarted my app ok 403 acess denied with test i can login and register
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
should i go back to auth/** ?
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
ok so the authenticate is not letting us get the test
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
postman?
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
with the test
Itsurran
ItsurranOP13mo ago
No description
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
yes Should we use help ping on this
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
Okej want me to send my everything with jwt invloved?
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Itsurran
ItsurranOP13mo ago
Yh thats why i ask if we should use help ping maybe someone that can jwt better than us find the problem
dan1st
dan1st13mo ago
Do you have a filter doing the authentication?
Itsurran
ItsurranOP13mo ago
package com.Nem.demo.config;

import com.Nem.demo.token.TokenRepository;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

private final JwtService jwtService;

private final UserDetailsService userDetailsService;

private final TokenRepository tokenRepository;

@Override
protected void doFilterInternal
(@NonNull HttpServletRequest request,
@NonNull HttpServletResponse response,
@NonNull FilterChain filterChain)
throws ServletException, IOException {
final String authHeader = request.getHeader("Authorization");
final String jwt;
final String userEmail;
if (authHeader == null || !authHeader.startsWith(("Bearer "))) {
filterChain.doFilter(request, response);
return;
}
jwt = authHeader.substring(7);
userEmail = jwtService.extractUsername(jwt);
if (userEmail != null && SecurityContextHolder.getContext().getAuthentication() == null){
UserDetails userDetails = this.userDetailsService.loadUserByUsername(userEmail);
var isTokenValid = tokenRepository.findByToken(jwt)
.map(t -> !t.isExpired() && !t.isRevoked())
.orElse(false);
if(jwtService.isTokenValid(jwt, userDetails) && isTokenValid){
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
userDetails,
null,
userDetails.getAuthorities()
);
authToken.setDetails(
new WebAuthenticationDetailsSource().buildDetails(request)
);
SecurityContextHolder.getContext().setAuthentication(authToken);
}
}
filterChain.doFilter(request, response);
}

}
package com.Nem.demo.config;

import com.Nem.demo.token.TokenRepository;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

private final JwtService jwtService;

private final UserDetailsService userDetailsService;

private final TokenRepository tokenRepository;

@Override
protected void doFilterInternal
(@NonNull HttpServletRequest request,
@NonNull HttpServletResponse response,
@NonNull FilterChain filterChain)
throws ServletException, IOException {
final String authHeader = request.getHeader("Authorization");
final String jwt;
final String userEmail;
if (authHeader == null || !authHeader.startsWith(("Bearer "))) {
filterChain.doFilter(request, response);
return;
}
jwt = authHeader.substring(7);
userEmail = jwtService.extractUsername(jwt);
if (userEmail != null && SecurityContextHolder.getContext().getAuthentication() == null){
UserDetails userDetails = this.userDetailsService.loadUserByUsername(userEmail);
var isTokenValid = tokenRepository.findByToken(jwt)
.map(t -> !t.isExpired() && !t.isRevoked())
.orElse(false);
if(jwtService.isTokenValid(jwt, userDetails) && isTokenValid){
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
userDetails,
null,
userDetails.getAuthorities()
);
authToken.setDetails(
new WebAuthenticationDetailsSource().buildDetails(request)
);
SecurityContextHolder.getContext().setAuthentication(authToken);
}
}
filterChain.doFilter(request, response);
}

}
yes sir
dan1st
dan1st13mo ago
Did you try debugging that filter? Is it getting executed?
Itsurran
ItsurranOP13mo ago
Nope nope Working perfectly, i mean when i had the id as int i could ge the user id in postman with the userdetails but somehow i wanted the int to be a uuid so i change places everywhere and now im getting a 403 trying to get the user id with the uuid in the postman
dan1st
dan1st13mo ago
maybe check whether it's getting executed
Itsurran
ItsurranOP13mo ago
Should i log it?
dan1st
dan1st13mo ago
I would use a breakpoint/debugger
JavaBot
JavaBot13mo ago
It looks like you are having issues with debugging or issues that can be solved using a debugger. Check out this article on dev.java to see how debugging works and how to use a debugger. This Stack Overflow question and its answers also explain debugging in general. These links describe how to use the debugger in some IDEs: • Debugging in IntelliJDebugging in Eclipse
Itsurran
ItsurranOP13mo ago
from what row should i use the breakpoint at UserDetails userDetails = this.userDetailsService.loadUserByUsername(userEmail); here?
dan1st
dan1st13mo ago
I would add it here: final String authHeader = request.getHeader("Authorization");
Itsurran
ItsurranOP13mo ago
should i add anything here or just done
No description
dan1st
dan1st13mo ago
just run it in debug mode and check whether it is executed
Itsurran
ItsurranOP13mo ago
nope its running
Itsurran
ItsurranOP13mo ago
No description
dan1st
dan1st13mo ago
and you made a request with the JWT?
Itsurran
ItsurranOP13mo ago
and nothing in my threads & variable oh ok 1 sec sry
dan1st
dan1st13mo ago
the filter should be executed when you make a request with a JWT, right?
Itsurran
ItsurranOP13mo ago
Im stuck here and also
No description
Itsurran
ItsurranOP13mo ago
No description
dan1st
dan1st13mo ago
so the breakpoint is executed? Is the line with the breakpoint highlighted?
Itsurran
ItsurranOP13mo ago
yes its highlighted rn
dan1st
dan1st13mo ago
ok so you have a step over button, right? check this for debugging
Itsurran
ItsurranOP13mo ago
I followed the instruction but i dont know what im looking for, iknow now the highlighted one is not executed and i a step over button but im not familiar where its getting me at
Itsurran
ItsurranOP13mo ago
when i did a step over button
No description
dan1st
dan1st13mo ago
No description
dan1st
dan1st13mo ago
with that, you can move to the next instruction and it shoulda show you what the program is doing+
Itsurran
ItsurranOP13mo ago
yh i did that
Itsurran
ItsurranOP13mo ago
No description
dan1st
dan1st13mo ago
did it move the blue thing down? oh
dan1st
dan1st13mo ago
here
No description
dan1st
dan1st13mo ago
it didn't find an authorization header
dan1st
dan1st13mo ago
btw you can use that button to let the application continue
No description
Itsurran
ItsurranOP13mo ago
ok lemme start over 1 sec actually intressting to learn this, thanks for ur time
JavaBot
JavaBot13mo ago
If you are finished with your post, please close it. If you are not, please ignore this message. Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.
dan1st
dan1st13mo ago
you mean debugging?
Itsurran
ItsurranOP13mo ago
yes, ive know about this but never took it seriously
dan1st
dan1st13mo ago
I really recommend you to check out https://dev.java/learn/debugging/
Dev.java: The Destination for Java Developers
Debugging in Java - Dev.java
Learning how to use a debugger
Itsurran
ItsurranOP13mo ago
ok just quick question when i start over, should i use endpoint register or login for the debug?
dan1st
dan1st13mo ago
it explains it better than I am able to do right now (and I originally requested it and reviewed it when it was written)
Itsurran
ItsurranOP13mo ago
ah i see
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
so im getting a null in my header
dan1st
dan1st13mo ago
looks like it How are you supplying the JWT token? when making the request
Itsurran
ItsurranOP13mo ago
in my authneticationService
package com.Nem.demo.auth;

import com.Nem.demo.config.JwtService;
import com.Nem.demo.token.Token;
import com.Nem.demo.token.TokenRepository;
import com.Nem.demo.token.TokenType;
import com.Nem.demo.user.Role;
import com.Nem.demo.user.User;
import com.Nem.demo.user.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class AuthenticationService {

private final UserRepository repository;

private final TokenRepository tokenRepository;

private final PasswordEncoder passwordEncoder;

private final JwtService jwtService;

private final AuthenticationManager authenticationManager;

public AuthenticationResponse register(RegisterRequest request) {
var user = User.builder()
.firstname(request.getFirstname())
.lastname(request.getLastname())
.email(request.getEmail())
.password(passwordEncoder.encode(request.getPassword()))
.role(Role.USER)
.build();
var savedUser = repository.save(user);
var jwtToken = jwtService.generateToken(user);
saveUserToken(savedUser, jwtToken);
return AuthenticationResponse.builder()
.token(jwtToken)
.build();
}

public AuthenticationResponse authenticate(AuthenticationRequest request) {
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
request.getEmail(),
request.getPassword()
)
);
var user = repository.findByEmail(request.getEmail())
.orElseThrow();
var jwtToken = jwtService.generateToken(user);
revokeAllUserTokens(user);
saveUserToken(user, jwtToken);
return AuthenticationResponse.builder()
.token(jwtToken)
.build();
}
private void revokeAllUserTokens(User user) {
var validUserTokens = tokenRepository.findAllValidTokensByUser(user.getId());
if(validUserTokens.isEmpty())
return;
validUserTokens.forEach(t -> {
t.setExpired(true);
t.setRevoked(true);
});
tokenRepository.saveAll(validUserTokens);
}

private void saveUserToken(User user, String jwtToken) {
var token = Token.builder()
.user(user)
.token(jwtToken)
.tokenType(TokenType.BEARER)
.revoked(false)
.expired(false)
.build();
tokenRepository.save(token);
}
}
package com.Nem.demo.auth;

import com.Nem.demo.config.JwtService;
import com.Nem.demo.token.Token;
import com.Nem.demo.token.TokenRepository;
import com.Nem.demo.token.TokenType;
import com.Nem.demo.user.Role;
import com.Nem.demo.user.User;
import com.Nem.demo.user.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class AuthenticationService {

private final UserRepository repository;

private final TokenRepository tokenRepository;

private final PasswordEncoder passwordEncoder;

private final JwtService jwtService;

private final AuthenticationManager authenticationManager;

public AuthenticationResponse register(RegisterRequest request) {
var user = User.builder()
.firstname(request.getFirstname())
.lastname(request.getLastname())
.email(request.getEmail())
.password(passwordEncoder.encode(request.getPassword()))
.role(Role.USER)
.build();
var savedUser = repository.save(user);
var jwtToken = jwtService.generateToken(user);
saveUserToken(savedUser, jwtToken);
return AuthenticationResponse.builder()
.token(jwtToken)
.build();
}

public AuthenticationResponse authenticate(AuthenticationRequest request) {
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
request.getEmail(),
request.getPassword()
)
);
var user = repository.findByEmail(request.getEmail())
.orElseThrow();
var jwtToken = jwtService.generateToken(user);
revokeAllUserTokens(user);
saveUserToken(user, jwtToken);
return AuthenticationResponse.builder()
.token(jwtToken)
.build();
}
private void revokeAllUserTokens(User user) {
var validUserTokens = tokenRepository.findAllValidTokensByUser(user.getId());
if(validUserTokens.isEmpty())
return;
validUserTokens.forEach(t -> {
t.setExpired(true);
t.setRevoked(true);
});
tokenRepository.saveAll(validUserTokens);
}

private void saveUserToken(User user, String jwtToken) {
var token = Token.builder()
.user(user)
.token(jwtToken)
.tokenType(TokenType.BEARER)
.revoked(false)
.expired(false)
.build();
tokenRepository.save(token);
}
}
and here is how i generate the token
package com.Nem.demo.config;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

@Service
public class JwtService {
private static final String SECRET_KEY = "ac274103a56c9e0fe03c1c3cbbafa1acadca5f61f3c89853c6bd35fea60b6c39";
public String extractUsername(String token) {
return extractClaim(token, Claims::getSubject);
}

public <T> T extractClaim(String token, Function<Claims, T> claimsResolver){
final Claims claims = extractAllClaims(token);
return claimsResolver.apply(claims);
}

public String generateToken(UserDetails userDetails){
return generateToken(new HashMap<>(), userDetails);
}

public String generateToken(
Map<String, Object> extraClaims,
UserDetails userDetails
) {
return Jwts
.builder()
.setClaims(extraClaims)
.setSubject(userDetails.getUsername())
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 24 ))
.signWith(getSignInKey(), SignatureAlgorithm.HS256)
.compact();
}

public boolean isTokenValid(String token, UserDetails userDetails){
final String username = extractUsername(token);
return (username.equals(userDetails.getUsername())) && !isTokenexpired(token);
}

private boolean isTokenexpired(String token) {
return extractExipriation(token).before(new Date());
}

private Date extractExipriation(String token) {
return extractClaim(token, Claims::getExpiration);
}

private Claims extractAllClaims(String token){
return Jwts.
parserBuilder()
.setSigningKey(getSignInKey())
.build()
.parseClaimsJws(token)
.getBody();
}

private Key getSignInKey() {
byte[] keyBytes = Decoders.BASE64.decode(SECRET_KEY);
return Keys.hmacShaKeyFor(keyBytes);
}

}
package com.Nem.demo.config;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

@Service
public class JwtService {
private static final String SECRET_KEY = "ac274103a56c9e0fe03c1c3cbbafa1acadca5f61f3c89853c6bd35fea60b6c39";
public String extractUsername(String token) {
return extractClaim(token, Claims::getSubject);
}

public <T> T extractClaim(String token, Function<Claims, T> claimsResolver){
final Claims claims = extractAllClaims(token);
return claimsResolver.apply(claims);
}

public String generateToken(UserDetails userDetails){
return generateToken(new HashMap<>(), userDetails);
}

public String generateToken(
Map<String, Object> extraClaims,
UserDetails userDetails
) {
return Jwts
.builder()
.setClaims(extraClaims)
.setSubject(userDetails.getUsername())
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 24 ))
.signWith(getSignInKey(), SignatureAlgorithm.HS256)
.compact();
}

public boolean isTokenValid(String token, UserDetails userDetails){
final String username = extractUsername(token);
return (username.equals(userDetails.getUsername())) && !isTokenexpired(token);
}

private boolean isTokenexpired(String token) {
return extractExipriation(token).before(new Date());
}

private Date extractExipriation(String token) {
return extractClaim(token, Claims::getExpiration);
}

private Claims extractAllClaims(String token){
return Jwts.
parserBuilder()
.setSigningKey(getSignInKey())
.build()
.parseClaimsJws(token)
.getBody();
}

private Key getSignInKey() {
byte[] keyBytes = Decoders.BASE64.decode(SECRET_KEY);
return Keys.hmacShaKeyFor(keyBytes);
}

}
dan1st
dan1st13mo ago
I meant where you set it in postman or whatever
Itsurran
ItsurranOP13mo ago
I'm not, unless i wanna logout i use the bearer token
Itsurran
ItsurranOP13mo ago
No description
dan1st
dan1st13mo ago
Well if you want to access it, you need to provide the token..? in every request that requires authentication
Itsurran
ItsurranOP13mo ago
Ye here
No description
Itsurran
ItsurranOP13mo ago
i post it there and when im trying to get a user id i get a 403 with access denied But i can perfectly register a user, login with a user and logout with a user wait
Itsurran
ItsurranOP13mo ago
Correct picture when sending it
No description
Itsurran
ItsurranOP13mo ago
No description
No description
Itsurran
ItsurranOP13mo ago
Console
dan1st
dan1st13mo ago
Can you show the complete stack trace of the second image here?
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
Im logged in now, and also have passed the right token in postman
dan1st
dan1st13mo ago
Can you please share the whole thing as text? not as an image just paste it in here
Itsurran
ItsurranOP13mo ago
Itsurran
ItsurranOP13mo ago
If necessary i can screenshare for you Maybe you can take a better look
dan1st
dan1st13mo ago
If you debug the filter again (this time using the header), what happens?
Itsurran
ItsurranOP13mo ago
Which one the bearer header or auth header
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
Shows my bearer that i have passed in Should i resume the program?
dan1st
dan1st13mo ago
if you continue stepping over, where does the blue line move?
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
this was the user/{id} with the bearer token in postman incase ur wondering
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
error here
dan1st
dan1st13mo ago
Does it stop after that line?
Itsurran
ItsurranOP13mo ago
no if i step over it just keep going down and down
dan1st
dan1st13mo ago
until where?
Itsurran
ItsurranOP13mo ago
the whole filter
dan1st
dan1st13mo ago
What does loadUserByUsername do? Can you show your implementation? And the class of the object it returns?
Itsurran
ItsurranOP13mo ago
public interface UserDetailsService {

/**
* Locates the user based on the username. In the actual implementation, the search
* may possibly be case sensitive, or case insensitive depending on how the
* implementation instance is configured. In this case, the <code>UserDetails</code>
* object that comes back may have a username that is of a different case than what
* was actually requested..
* @param username the username identifying the user whose data is required.
* @return a fully populated user record (never <code>null</code>)
* @throws UsernameNotFoundException if the user could not be found or the user has no
* GrantedAuthority
*/
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;

}
public interface UserDetailsService {

/**
* Locates the user based on the username. In the actual implementation, the search
* may possibly be case sensitive, or case insensitive depending on how the
* implementation instance is configured. In this case, the <code>UserDetails</code>
* object that comes back may have a username that is of a different case than what
* was actually requested..
* @param username the username identifying the user whose data is required.
* @return a fully populated user record (never <code>null</code>)
* @throws UsernameNotFoundException if the user could not be found or the user has no
* GrantedAuthority
*/
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;

}
ok i will show u everyhing i just watnt this to work :p User Class
package com.Nem.demo.user;


import com.Nem.demo.token.Token;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.UUID;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Builder
@Table(name = "users")
public class User implements UserDetails {

@Id
@GeneratedValue(strategy = GenerationType.UUID)
private UUID id;

private String firstname;

private String lastname;

private String email;

private String password;

@Enumerated(EnumType.STRING)
private Role role;


@OneToMany(mappedBy = "user")
private List<Token> tokens;

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return List.of(new SimpleGrantedAuthority(role.name()));
}

@Override
public String getPassword() {
return password;
}

@Override
public String getUsername() {
return email;
}

@Override
public boolean isAccountNonExpired() {
return true;
}

@Override
public boolean isAccountNonLocked() {
return true;
}

@Override
public boolean isCredentialsNonExpired() {
return true;
}

@Override
public boolean isEnabled() {
return true;
}
}
package com.Nem.demo.user;


import com.Nem.demo.token.Token;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.UUID;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Builder
@Table(name = "users")
public class User implements UserDetails {

@Id
@GeneratedValue(strategy = GenerationType.UUID)
private UUID id;

private String firstname;

private String lastname;

private String email;

private String password;

@Enumerated(EnumType.STRING)
private Role role;


@OneToMany(mappedBy = "user")
private List<Token> tokens;

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return List.of(new SimpleGrantedAuthority(role.name()));
}

@Override
public String getPassword() {
return password;
}

@Override
public String getUsername() {
return email;
}

@Override
public boolean isAccountNonExpired() {
return true;
}

@Override
public boolean isAccountNonLocked() {
return true;
}

@Override
public boolean isCredentialsNonExpired() {
return true;
}

@Override
public boolean isEnabled() {
return true;
}
}
UserRepository
package com.Nem.demo.user;

import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;
import java.util.Optional;
import java.util.UUID;


public interface UserRepository extends JpaRepository<User, UUID> {

Optional<User> findByEmail(String email);

boolean existsByFirstname (String firstname);
boolean existsByEmail(String email);

List<User> findAllBy();
User findUserById(UUID id);


}
package com.Nem.demo.user;

import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;
import java.util.Optional;
import java.util.UUID;


public interface UserRepository extends JpaRepository<User, UUID> {

Optional<User> findByEmail(String email);

boolean existsByFirstname (String firstname);
boolean existsByEmail(String email);

List<User> findAllBy();
User findUserById(UUID id);


}
dan1st
dan1st13mo ago
I meant your implementation Can you try adding @ToString.Exclude to tokens here? (from lombok)
Itsurran
ItsurranOP13mo ago
like this?
No description
dan1st
dan1st13mo ago
yes
Itsurran
ItsurranOP13mo ago
debug or run normally
dan1st
dan1st13mo ago
yours to decide
Itsurran
ItsurranOP13mo ago
ok
dan1st
dan1st13mo ago
because the exception means that it is calling toString of that and that tries to load tokens (which is failing) which you probably don't want there Also storing a list of tokens for each user sounds like a bad idea
Itsurran
ItsurranOP13mo ago
Im not even getting a response in postman
Itsurran
ItsurranOP13mo ago
Itsurran
ItsurranOP13mo ago
console Anyone?
dan1st
dan1st13mo ago
Are you still in debug mode? Is the program suspended? oh nvm the issue is probably the StackOverflowError
Itsurran
ItsurranOP13mo ago
yep stacckoverflowerror null
dan1st
dan1st13mo ago
you seem to have a circular dependency between two data classes which are deserialized
Itsurran
ItsurranOP13mo ago
deserialized? ccan it be betwen @OneToMany(fetch = FetchType.EAGER, mappedBy = "user") private List<Token> tokens; and @ManyToOne @JoinColumn(name = "user_id") private User user;
dan1st
dan1st13mo ago
yes well probably serialized Is the application converting a user to JSON here? I guess the issue is that the user contains a list of tokens and the token contain a user so you have something like
{
name: "a",
tokens:[{
text: "aaaa",
user: {
name: "a",
tokens:[{
text: "aaaa",
user: {
name: "a",
tokens:[{
text: "aaaa",
user: {
name: "a",
tokens:[{
text: "aaaa",
user: {...}
}]
}
}]
}
}]
}
}]
}
{
name: "a",
tokens:[{
text: "aaaa",
user: {
name: "a",
tokens:[{
text: "aaaa",
user: {
name: "a",
tokens:[{
text: "aaaa",
user: {
name: "a",
tokens:[{
text: "aaaa",
user: {...}
}]
}
}]
}
}]
}
}]
}
Itsurran
ItsurranOP13mo ago
Yes
dan1st
dan1st13mo ago
then I guess that's what happens essentially just that it would happen infinitely often resulting in the said issue
Itsurran
ItsurranOP13mo ago
Not following with rn, what should I do or think of?
dan1st
dan1st13mo ago
Does your token class contain a field with the user? (it's essentially this issue)
Itsurran
ItsurranOP13mo ago
Yes
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
in my token and u think this is the issue ?
dan1st
dan1st13mo ago
yes
Itsurran
ItsurranOP13mo ago
oooo ok never thought of it
dan1st
dan1st13mo ago
What's the JSON you are expecting? for a user
Itsurran
ItsurranOP13mo ago
ok sec gonna reopen my postman had to restart my pc
dan1st
dan1st13mo ago
I am not asking you what happens right now I want to know what JSON you are expecting
Itsurran
ItsurranOP13mo ago
my userdetails something liek dis
dan1st
dan1st13mo ago
ok so you are expecting the tokens to be exported which in turn contain the user which in turn contains the tokens which in turn contains the user which in turn contains the tokens..?
Itsurran
ItsurranOP13mo ago
oh damn ok i understand the point
dan1st
dan1st13mo ago
i.e. you would expect an infinitely big json object? The easiest way to get rid of that issue is to just not include the tokens in the JSON data Is that ok for you?
Itsurran
ItsurranOP13mo ago
Yes
dan1st
dan1st13mo ago
ok then you can just add @JsonIgnore to th tokens just like the @ToString.Exclude this means "ignore that field when creating the JSON"
Itsurran
ItsurranOP13mo ago
yh, ok on user class i should both have the @toString.Exclude and jsignore sry for the tag
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
good?
dan1st
dan1st13mo ago
yes
Itsurran
ItsurranOP13mo ago
ok sec
dan1st
dan1st13mo ago
But I do have another question Why do you use JWT and store a list of tokens for each user at all?
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
Letsgoooo!!
dan1st
dan1st13mo ago
and if you need to store a list of tokens for each user, why are you using JWTs? . also including the password hash is probably not the best idea, just saying
Itsurran
ItsurranOP13mo ago
I had a problem with jwt before and i saw someone solve it with putting the jwt in a table
JavaBot
JavaBot13mo ago
If you are finished with your post, please close it. If you are not, please ignore this message. Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.
Itsurran
ItsurranOP13mo ago
should i not? jsoningore on it to?
dan1st
dan1st13mo ago
if you don't want to include it
Itsurran
ItsurranOP13mo ago
whats the recommendation from you? like im still a newbie and ive learn so much from you just this time
dan1st
dan1st13mo ago
Well the whole point of JWT is that you don't need to store all JWTs but the token itself proves that it is correct (using cryptography/signing if you are interested in that)
Itsurran
ItsurranOP13mo ago
Ok so 2 things right now that i need to have checked and probably good to have is that jsonignore on hashpw and not have the jwt token stored but can i have the jwt token stored for now and later fixed? or will it be a problem or is it better to have it fix rn
dan1st
dan1st13mo ago
well there's just no need to store it it isn't a problem except unnecessary complexity and you need the space (memory and disk space) to store it
Itsurran
ItsurranOP13mo ago
Ok, should i just delete the tokenclass wont it break alot of things
dan1st
dan1st13mo ago
no
Itsurran
ItsurranOP13mo ago
i never though a jsignore would solve tihs 😮
dan1st
dan1st13mo ago
I would - make a backup of the project (since it seems to work now) - remove the list of tokens from the user - fix the errors you get from doing that - try to get the project working again btw it's jsonignore, not jsignore
Itsurran
ItsurranOP13mo ago
yh sry Ok so im gonna push this to github then remove token from the user
dan1st
dan1st13mo ago
you can do that
Itsurran
ItsurranOP13mo ago
but wont i need it for auth the token
dan1st
dan1st13mo ago
well you are validating the token, right? the client sends you the token
Itsurran
ItsurranOP13mo ago
Yh true sry
dan1st
dan1st13mo ago
and when validating, you check whether it's correct
Itsurran
ItsurranOP13mo ago
btw a quick question
dan1st
dan1st13mo ago
no need to be sorry
Itsurran
ItsurranOP13mo ago
before i sent the application.properties to my github which is wrong right, i heard i either need to delete the github and make a new repo or clear the cache and send it but how can i clear the cache and send it since i have few commits i want to save now i have this app ### src/main/resources/application.properties on my gitignore
dan1st
dan1st13mo ago
including the application.properties is not wrong per-se - but you need to make sure you are not including any credentials there you can't really do that
Itsurran
ItsurranOP13mo ago
yh i have my whole passwored and datab ase information in application Ok so whats the catch
dan1st
dan1st13mo ago
Also if you just added another commit, that commit would still contain information about the previous state I would still reset it
Itsurran
ItsurranOP13mo ago
so i need to delete the repo
dan1st
dan1st13mo ago
Did you delete the repo and then added another commit to the project and pushed it to a new repo? or did you amend the commit?
Itsurran
ItsurranOP13mo ago
no i had this repo when i started and i forgot to ignore the application the application.properties is in the repo rn
dan1st
dan1st13mo ago
What did you do after deleting the repo? ah ok
Itsurran
ItsurranOP13mo ago
i didnt delete it but my friend told me i can either clear the cache
dan1st
dan1st13mo ago
Did you add it in the last commit?
Itsurran
ItsurranOP13mo ago
or make a new repo yh
Itsurran
ItsurranOP13mo ago
No description
dan1st
dan1st13mo ago
Was it added in the last commit?
Itsurran
ItsurranOP13mo ago
yes 4 days ago was my last commit
dan1st
dan1st13mo ago
ok then you can change the commit if you didn't create another commit afterwards
Itsurran
ItsurranOP13mo ago
nope
dan1st
dan1st13mo ago
That's called "amending" the commit
Itsurran
ItsurranOP13mo ago
i havnt
dan1st
dan1st13mo ago
How are you typically pushing to GitHub?
Itsurran
ItsurranOP13mo ago
terminal git status git add . git commit -m git push
dan1st
dan1st13mo ago
ok so you first need to remove the application.properties from the local repository without deleting the file you want to tell git the file is gone without actually removing it What's the output of git status?
Itsurran
ItsurranOP13mo ago
No description
dan1st
dan1st13mo ago
Is anything green in there?
Itsurran
ItsurranOP13mo ago
but i have this in gitignore nope i havnt done git add . yet
dan1st
dan1st13mo ago
that isn't enough if you add it to the gitignore, it will continue to stay there
Itsurran
ItsurranOP13mo ago
yh
dan1st
dan1st13mo ago
you can use git rm --cached src\main\resources\application.properties
Itsurran
ItsurranOP13mo ago
ok so that first in the terminal?
dan1st
dan1st13mo ago
that tells git to remove the file but not actually delete it from your file system yes you can also use git add .gitignore if you want to add the gitignore
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
and now
dan1st
dan1st13mo ago
(NOT git add .)
Itsurran
ItsurranOP13mo ago
the enormal git add .
dan1st
dan1st13mo ago
no
Itsurran
ItsurranOP13mo ago
so git add .gitignore ?
dan1st
dan1st13mo ago
ok so what do you want to change in the last commit?
Itsurran
ItsurranOP13mo ago
applicitaion.properties
dan1st
dan1st13mo ago
type git status and it should show the application.properties as deleted
Itsurran
ItsurranOP13mo ago
ahhhh
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
okkkk
dan1st
dan1st13mo ago
above that You are the only one working on that project, right?
Itsurran
ItsurranOP13mo ago
yes
dan1st
dan1st13mo ago
Is the application.properties above that? shown as deleted?
Itsurran
ItsurranOP13mo ago
in git status or in github repo? in git status its deleted
dan1st
dan1st13mo ago
git status yeah ok
Itsurran
ItsurranOP13mo ago
yh
dan1st
dan1st13mo ago
Then you can apply that change locally you can change the last commit this works with the command git commit --amend --no-edit This means "apply the current changes (the deletion) by changing my last commit. Do not change the commit message. Do not create a new commit."
Itsurran
ItsurranOP13mo ago
i see
No description
Itsurran
ItsurranOP13mo ago
yh delete mode at the lats row
dan1st
dan1st13mo ago
yes
Itsurran
ItsurranOP13mo ago
its still in github, is it becuse its not pushed?
dan1st
dan1st13mo ago
yes but with that, you won't be able to push since you have a different (conflicting) history than GitHub you can tell git to overwrite the history on GitHub this is a force push - something you shouldn't do when there are other people working on the project
Itsurran
ItsurranOP13mo ago
Okej
dan1st
dan1st13mo ago
it essentially means "I don't care what's on the other side (GitHub), just overwrite it, my changes are all I want" you can do that with git push --force-with-lease
Itsurran
ItsurranOP13mo ago
yh its gone now but i can still view it on my commit
Itsurran
ItsurranOP13mo ago
No description
dan1st
dan1st13mo ago
? How did you get to the commit? But yes it isn't completely gone
Itsurran
ItsurranOP13mo ago
History, i see so it will only be gone from the current change and not the past
dan1st
dan1st13mo ago
Is it actually in the history? If it is, then you added another commit you didn't tell me about after adding the file but if it's not in the history, it's actually GitHub caching it
Itsurran
ItsurranOP13mo ago
I see my mistake, i have 2 commits on my last commit its gone but not the othe one. Though u meant if i had commited like recently something.
Itsurran
ItsurranOP13mo ago
my last commit
No description
Itsurran
ItsurranOP13mo ago
and my first commits its till there
Itsurran
ItsurranOP13mo ago
my first commit
No description
dan1st
dan1st13mo ago
ok yes there is another commit making it more difficult
Itsurran
ItsurranOP13mo ago
ah ok
dan1st
dan1st13mo ago
Which commit did you add the password in?
Itsurran
ItsurranOP13mo ago
first commit
dan1st
dan1st13mo ago
that one? if you click on Load diff there, is the password shown?
Itsurran
ItsurranOP13mo ago
yes look i have 4 commits, first commit was nothing added the second commit was jwtfilter and no sql pw invlode but my third is sql involed and my fourth is my last commit
Itsurran
ItsurranOP13mo ago
No description
dan1st
dan1st13mo ago
and which one added the password to the application.propertiee?
Itsurran
ItsurranOP13mo ago
* my third commit and my last commit
dan1st
dan1st13mo ago
Do you care about having the previous commits?
Itsurran
ItsurranOP13mo ago
ope nop i can even restart if its necessary
dan1st
dan1st13mo ago
ok then you can just delete the git repository I can show you how
Itsurran
ItsurranOP13mo ago
😂 that i know how hahah
dan1st
dan1st13mo ago
How? I said git repository, not GitHub repository
Itsurran
ItsurranOP13mo ago
oh ok no idk how then
dan1st
dan1st13mo ago
so in your project, there's a .git folder
Itsurran
ItsurranOP13mo ago
correct
dan1st
dan1st13mo ago
if you delete that folder, git won't know about the commits
Itsurran
ItsurranOP13mo ago
this on e right?
No description
dan1st
dan1st13mo ago
and you can just use git init, git add . etc again no
Itsurran
ItsurranOP13mo ago
AHHHH OK i kn ow
dan1st
dan1st13mo ago
I think IntelliJ doesn't even show that folder
Itsurran
ItsurranOP13mo ago
which one the hidden one yh waity wait
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
this one
dan1st
dan1st13mo ago
yes
Itsurran
ItsurranOP13mo ago
correct
dan1st
dan1st13mo ago
if you delete that, git (not GitHub) won't know about the commits any more
Itsurran
ItsurranOP13mo ago
oke
dan1st
dan1st13mo ago
Did you do it?
Itsurran
ItsurranOP13mo ago
deleted
dan1st
dan1st13mo ago
now you can use git init again and it will create a new repository
Itsurran
ItsurranOP13mo ago
done
dan1st
dan1st13mo ago
then the whole git add ., git commit -m "your commit message here" and git remote origin https://github.com/yourusername/yourrepositoryname
Itsurran
ItsurranOP13mo ago
ok sec
dan1st
dan1st13mo ago
and you need to use a force push (git push -f) again or you also delete the repository on GitHub and create it again as well then you can use the normal git push
Itsurran
ItsurranOP13mo ago
isnt it git remote add origin?
dan1st
dan1st13mo ago
yeah my fault
Itsurran
ItsurranOP13mo ago
No description
dan1st
dan1st13mo ago
oh you already created it? What's the output of git log?
Itsurran
ItsurranOP13mo ago
Wait so the part i think ive missed is that i need to create a new repo in github and use that reponame and not my current one?
dan1st
dan1st13mo ago
you can also use the same name again
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
git log
dan1st
dan1st13mo ago
I don't think you properly deleted the .git folder maybe you deleted the .git folder of another project?
Itsurran
ItsurranOP13mo ago
yh true now
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
but i cant git push -f don't i need to do git push origin main ?
dan1st
dan1st13mo ago
yes You need to commit before pushing
Itsurran
ItsurranOP13mo ago
done
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
that Wait just lemme do this easier lemme delete this GITHUb repo and start over
Itsurran
ItsurranOP13mo ago
New Github repo
No description
Itsurran
ItsurranOP13mo ago
Ok now im gonna delete everthing associated with user & token
dan1st
dan1st13mo ago
The new one doesn't contain anything with user/token, right?
Itsurran
ItsurranOP13mo ago
Doesnt contain anything my application properties but now im gonna delete everything assosiated with the user token and push again
dan1st
dan1st13mo ago
oh that
Itsurran
ItsurranOP13mo ago
because as u said, unncessary usage
dan1st
dan1st13mo ago
yeah sure do that Also I recommend you to do the following: Before doing anything security related that's important (e.g. at a company), make sure you really understand what you are doing and what the things you are working with are
Itsurran
ItsurranOP13mo ago
Do you have any following guide i can really improve by, docs/tutorials u name it.
dan1st
dan1st13mo ago
on what specifically?
Itsurran
ItsurranOP13mo ago
Security, desgin patterns, more about debugging. Like everythng in general just to improve better and better. Im taking my degree on summer and i want to work with spring boot backend and reactjs frontend so a fullstack dev Like frontend i know liek 80% what im doing cause i put alot of time on it but its backend time now until summer I just realized also im handling my logout service with storedtokens
jwt = authHeader.substring(7);
var storedToken = tokenRepository.findByToken(jwt)
.orElse(null);
if(storedToken != null) {
storedToken.setExpired(true);
storedToken.setRevoked(true);
tokenRepository.save(storedToken);
jwt = authHeader.substring(7);
var storedToken = tokenRepository.findByToken(jwt)
.orElse(null);
if(storedToken != null) {
storedToken.setExpired(true);
storedToken.setRevoked(true);
tokenRepository.save(storedToken);
and if i delete everything i will have problem with my logout I had other project i handle the logout with cookie
@PostMapping("/sign-out")
public ResponseEntity<String> logout(HttpServletRequest request, HttpServletResponse response) {
SecurityContextHolder.clearContext();
CookieClearingLogoutHandler cookieClearingLogoutHandler = new CookieClearingLogoutHandler("cookie");
cookieClearingLogoutHandler.logout(request, response, null);
return ResponseEntity.ok("Sign out successful");
}
@PostMapping("/sign-out")
public ResponseEntity<String> logout(HttpServletRequest request, HttpServletResponse response) {
SecurityContextHolder.clearContext();
CookieClearingLogoutHandler cookieClearingLogoutHandler = new CookieClearingLogoutHandler("cookie");
cookieClearingLogoutHandler.logout(request, response, null);
return ResponseEntity.ok("Sign out successful");
}
but ive heard that the cookie should not be handled in anyway maybe in http but nothing more
dan1st
dan1st13mo ago
for debugging, I already told you. For security and design patters, just look up the docs on the specific thing you need
Itsurran
ItsurranOP13mo ago
Yes sir, do you recommend that user have field with created at?
dan1st
dan1st13mo ago
if you don't store tokens, you don't need to delete them oh for revocation yeah if you need such a logout, that's a little bit more complicated ? you could have a set of all revoked tokens and remove them once they expire but generally: Do you really need a logout?
Itsurran
ItsurranOP13mo ago
Yes, i want a signout for a user so he/she can logout
dan1st
dan1st13mo ago
you could do that but the question is do you really need JWTs then?
Itsurran
ItsurranOP13mo ago
like stored jwts? or in general
dan1st
dan1st13mo ago
Why are you using JWTs when you have a login and a logout and everything in a database? assuming you don't have microservices
Itsurran
ItsurranOP13mo ago
What do you mean? No clue.
dan1st
dan1st13mo ago
why did you decide for JWTs?
Itsurran
ItsurranOP13mo ago
Idk i just learned it from beginning of my spring boot trip What do you think of it? By the way I never thanked you properly. Thank you Daniel for your kind and effort to this help, truly amazing you have you and other around here.
JavaBot
JavaBot13mo ago
If you are finished with your post, please close it. If you are not, please ignore this message. Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.
dan1st
dan1st13mo ago
JWT is a way of stateless authentication/authorization that means the token contains the information you need - which user, an expiration, possibly privileges and a signature that proves validity it's used in cases where you don't want to store a mapping between users and tokens where you want to have something like "if they have a valid token, they are authorized"
Itsurran
ItsurranOP13mo ago
Ok so basically I just have to delete that’s it’s creating a table with tokens but still generates a token to user Right?
dan1st
dan1st13mo ago
and they don't have revocation - once you create a token, it's valid until it expires (unless you write custom revocation logic which requires a bit of state) the issue is the logout - JWTs aren't really made for that the idea of JWTs is that they are short-lived so you don't need to log out
Itsurran
ItsurranOP13mo ago
True, but I have no other knowledge around a logout expect this.
dan1st
dan1st13mo ago
If you really want a logout, you could work around this
Itsurran
ItsurranOP13mo ago
I mean I need a logout endpoint in case a user want to logout?
dan1st
dan1st13mo ago
I mean one way is to let the client delete the token but someone who has the token would still be able to use it
Itsurran
ItsurranOP13mo ago
Okej
dan1st
dan1st13mo ago
or if you really want the token to be invalidated, you could store a blacklist of tokens
Itsurran
ItsurranOP13mo ago
I’ve heard about that About blacklisitng the tokens
dan1st
dan1st13mo ago
i.e. you store all non-expired invalidated tokens in a set or similar
Itsurran
ItsurranOP13mo ago
What would you do if u were me? What’s the best and modern way to do it I know it’s about preferences
dan1st
dan1st13mo ago
I would start without a logout then add it by first invalidating the token and then add the blacklisting logic
Itsurran
ItsurranOP13mo ago
Is that good way for security to? Blacklisting? Also what about cookies? How should I handle cookies?
dan1st
dan1st13mo ago
it requires these things - adding tokens to the blacklist when a user logs out - checking the blacklist when a user attempts to use a token (don't allow logging in with tokens in the blacklist) - remove tokens from the blacklist automatically when they are expired (e.g. check every 5min) if you do it properly, yes What about it? if you store the JWT in a cookie, delete the cookie when logging out
Itsurran
ItsurranOP13mo ago
Gonna watch over this more tomorrow! Interesting. Or actually now before I knock my self to sleep So I can store a jwt in a cookie and a cookie is associated with a user then the cookie gets executed whenever logging out? Right
dan1st
dan1st13mo ago
you can store it in a cookie but idk what do you mean with it getting executed
Itsurran
ItsurranOP13mo ago
Wait so when you mean by blacklisitng you mean a refresh token? Cause I know a little about refresh token
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
This what you meant right
dan1st
dan1st13mo ago
I meant the jwt itself which you normally don't invalidate if you have a refresh token, you'd need to invalidate that
JavaBot
JavaBot13mo ago
💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.
Itsurran
ItsurranOP13mo ago
I'm trying to implement that a user should only register with a invite, so i want a admin to generate a registeration key to send it over, but i read that i need to store those generation keys. Does that mean i need a table for it? Don't want to make same mistake as the jwt token(stored)
dan1st
dan1st13mo ago
yes, I would create a table for that
Itsurran
ItsurranOP13mo ago
But how does the generation for the key work? do i always need to go to the db or can i have it generate on the website?
dan1st
dan1st13mo ago
well you can write Java code that generates a random string using SecureRandom
Itsurran
ItsurranOP13mo ago
Daniel, im working on the frontend part a little bit and i fixed that i can register and authenticate as a user but im not getting the user id and i think its because im not inclouding the userid in the response, should i do it?
Itsurran
ItsurranOP13mo ago
No description
dan1st
dan1st13mo ago
?
Itsurran
ItsurranOP13mo ago
right here?
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
my frontend part im getting undefined
dan1st
dan1st13mo ago
oh if you want to add the user id, do that
Itsurran
ItsurranOP13mo ago
Thanks, i got another issue here
import { Navigate } from "react-router-dom";

const PrivateRoute = ({ children }) => {
const user = JSON.parse(localStorage.getItem("user"));
if (!user) {
return <Navigate to="/" />;
}

if (
user.role?.includes("ROLE_USER") ||
user.role?.includes("ROLE_PROVIDER")
) {
return <>{children}</>;
} else {
return <Navigate to="/login" />;
}
};

export default PrivateRoute;
import { Navigate } from "react-router-dom";

const PrivateRoute = ({ children }) => {
const user = JSON.parse(localStorage.getItem("user"));
if (!user) {
return <Navigate to="/" />;
}

if (
user.role?.includes("ROLE_USER") ||
user.role?.includes("ROLE_PROVIDER")
) {
return <>{children}</>;
} else {
return <Navigate to="/login" />;
}
};

export default PrivateRoute;
So im doing a logic here that if the user doesnt have the ROLE_USER OR ROLE_PROVIDER it shouldnt be let to these routes, but when i login with a user_role it doesnt let me go through.
No description
Itsurran
ItsurranOP13mo ago
package com.Nem.demo.user;

public enum Role {

ROLE_USER,

ROLE_PROVIDER,

}
package com.Nem.demo.user;

public enum Role {

ROLE_USER,

ROLE_PROVIDER,

}
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Builder
@Table(name = "users")
public class User implements UserDetails {

@Id
@GeneratedValue(strategy = GenerationType.UUID)
private UUID id;

private String firstname;

private String lastname;

private String email;

@JsonIgnore
private String password;

@Enumerated(EnumType.STRING)
private Role role;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Builder
@Table(name = "users")
public class User implements UserDetails {

@Id
@GeneratedValue(strategy = GenerationType.UUID)
private UUID id;

private String firstname;

private String lastname;

private String email;

@JsonIgnore
private String password;

@Enumerated(EnumType.STRING)
private Role role;
my user class Can it be that im not getting having a role in my authenticationresponse
dan1st
dan1st13mo ago
? what specifically is the problem?
Itsurran
ItsurranOP13mo ago
So when i try to login with my user that has role_user it should let me pass my privateroute right cause it only lets role_user role_provider to go through but its not letting me so im wondering can it be that im not inclouding any userdetails in my authenticationresponse? i only have id and jwt token as response right now
dan1st
dan1st13mo ago
I am not really experienced with angular what exactly is the response? I think it would need to be something like user.role == "ROLE_USER"
Itsurran
ItsurranOP13mo ago
Sec, im gonna try to have the role with the response and se maybe its lacking about it Yep it was lacking the response in authnetication
Itsurran
ItsurranOP13mo ago
now im getting it
No description
Itsurran
ItsurranOP13mo ago
and it went throught the private route Hey Daniel im getting error when sending my logout endpoint, :5173/login:1 Access to XMLHttpRequest at 'http://localhost:8080/api/v1/auth/logout' from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. I already have this @CrossOrigin(origins = "http://localhost:5173", maxAge = 3600, allowCredentials = "true") in my AuthenticationController but.... the logout endpoint doesnt happen there, it happens in my securirtyConfig
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.authorizeHttpRequests()
.requestMatchers("/api/v1/auth/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authenticationProvider(authenticationProvider)
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
.logout()
.logoutUrl("/api/v1/auth/logout")
.addLogoutHandler(logoutHandler)
.logoutSuccessHandler((request, response, authentication) -> SecurityContextHolder.clearContext()
);
return http.build();
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.authorizeHttpRequests()
.requestMatchers("/api/v1/auth/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authenticationProvider(authenticationProvider)
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
.logout()
.logoutUrl("/api/v1/auth/logout")
.addLogoutHandler(logoutHandler)
.logoutSuccessHandler((request, response, authentication) -> SecurityContextHolder.clearContext()
);
return http.build();
Does this mean i have to put a crossorigin in my securirtyConfig?
dan1st
dan1st13mo ago
Do you know what CORS means? Are you using cookies for anything?
Itsurran
ItsurranOP13mo ago
Yes its a policy that restrict from making request nope not yet
dan1st
dan1st13mo ago
What do you plan on using cookies for? Do you know why it's necessary?
Itsurran
ItsurranOP13mo ago
maybe have session tokens in a secure HTTPOnly cookie in the future yes preventing access against server etc
dan1st
dan1st13mo ago
then you should be very careful with both disabling CSRF and allowing CORS if you want to store the JWT in a cookie
Itsurran
ItsurranOP13mo ago
whys that
dan1st
dan1st13mo ago
Let's start with CSRF assuming your token is provided as a cookie then someone logs in and gets a token it's stored in a cookie Then they visit another website, evil.com which is malicious they can tell the browser to send a request to your backend and the browser happily includes the cookie
Itsurran
ItsurranOP13mo ago
and all user details ?
dan1st
dan1st13mo ago
For example, it could ask to request POST /user/delete
Itsurran
ItsurranOP13mo ago
ahhh shit so you have access to the backend
dan1st
dan1st13mo ago
that's what CSRF protects from
Itsurran
ItsurranOP13mo ago
okej
dan1st
dan1st13mo ago
it does that by requiring every request to include a csrf token because the other site cannot read the response
Itsurran
ItsurranOP13mo ago
so having CSRF disabled means other can have access
dan1st
dan1st13mo ago
so a CSRF token is added to each response and every request that changes something (e.g. POST) needs to contain that CSRF token and CORS is exactly that - the browser doesn't tell other sites about the responses - unless you allow it a simple solution to that is to not use cookies if you put it in localStorage and use JS to add it to the requests, you don't have that issue
Itsurran
ItsurranOP13mo ago
Okej so I'm not using a cookie rn for a user only jwt token and it gets validated after they logout or authenticate right
dan1st
dan1st13mo ago
How are you storing the jwt token?
Itsurran
ItsurranOP13mo ago
Same as before
dan1st
dan1st13mo ago
so you won't have that problem- yet which is?
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
in a table
dan1st
dan1st13mo ago
I meant the client
Itsurran
ItsurranOP13mo ago
User?
dan1st
dan1st13mo ago
yeah How is the token stored in the browser?
Itsurran
ItsurranOP13mo ago
localstorage
dan1st
dan1st13mo ago
ok yeah that's fine
Itsurran
ItsurranOP13mo ago
when logging in the token is sent with the userdetails wait
dan1st
dan1st13mo ago
localStorage is fine cookies would result in the aforementioned issue
Itsurran
ItsurranOP13mo ago
No description
Itsurran
ItsurranOP13mo ago
here is how im sending it Yes ive heard it so i wanna avoid it but a guy said i would use cookies for http something and nothing more
dan1st
dan1st13mo ago
so about CORS - browsers block who can read responses
Itsurran
ItsurranOP13mo ago
yes
dan1st
dan1st13mo ago
by default, it only allows it if it comes from the same domain/host/origin
Itsurran
ItsurranOP13mo ago
which is @CrossOrigin(origins = "*", maxAge = 3600) right?
dan1st
dan1st13mo ago
if your frontend is not at the same location as the backend, you need to allow it that would allow anyone to access the responses or anyone can send requests and read their responses
Itsurran
ItsurranOP13mo ago
same location? how do you mean? When i tried to authenticate before i got cors and this solved it @CrossOrigin(origins = "http://localhost:5173", maxAge = 3600, allowCredentials = "true")
dan1st
dan1st13mo ago
only the website example.com can make requests to example.com and read the responses if evil.com makes a response to example.com, it cannot read the response
Itsurran
ItsurranOP13mo ago
oh? so i need to
dan1st
dan1st13mo ago
yes, this allows localhost:5173 to send requests and read the responses
Itsurran
ItsurranOP13mo ago
communicate oh im getting it so now i need to add but where though should i add the cors to allow it to logout
dan1st
dan1st13mo ago
I think this video explains CORS well: https://youtu.be/bSJm8-zJTzQ
LiveOverflow
YouTube
The Same Origin Policy - Hacker History
In 1995 Netscape invented JavaScript (LiveScript) and it marked the start of client-side web security issues. In this video we explore this history and learn about the same origin policy (SOP). Cookies Explained: https://web.archive.org/web/19970605224124/http://help.netscape.com/kb/client/970226-2.html Netscape 2.0b1 LiveScript: https://web.ar...
dan1st
dan1st13mo ago
logout?
Itsurran
ItsurranOP13mo ago
Gonna watch it rn Yes because when im sending my logout endpoint im getting that cors error
dan1st
dan1st13mo ago
and https://youtu.be/KaEj_qZgiKY if you are interested
LiveOverflow
YouTube
CSRF Introduction and what is the Same-Origin Policy? - web 0x04
What is cross site request forgery and what does it have to do wwith the same-origin policy. -=[ 🔴 Stuff I use ]=- → Microphone:* https://geni.us/ntg3b → Graphics tablet:* https://geni.us/wacom-intuos → Camera#1 for streaming:* https://geni.us/sony-camera → Lens for streaming:* https://geni.us/sony-lense → Connect Camera#1 to PC:* https://gen...
dan1st
dan1st13mo ago
it's with all endpoints where you want to read the response
JavaBot
JavaBot13mo ago
Help Guidelines
1. Don't ask questions like "Can I ask ...?" or "Can someone help me?". It's easier for everyone involved if you provide a detailed description of your problem up-front; this makes it more likely for helpers to want to help, and more likely that you'll get an answer quickly. Please provide code snippets and error messages (if any) to help us help you! 2. Please create a post in <#1023632039829831811> for your questions. Do not use other people's posts for your questions. 3. You may use the /help ping command if your question is urgent. Abusing this will result in warnings and/or a ban. 4. Do not ask for help with exams or homework. You may ask for help with understanding individual concepts and parts of a question, but homework and exam questions that show little effort on your part will most likely go unanswered and may be removed. 5. Do not ask your question if you didn't at least try to solve the problem yourself, are ignorant, or, instead of trying to improve, ask repeating, simple, questions. 6. Format your code using Discord's triple-backtick syntax. 7. For reasons similar to those of Stack Overflow, we currently do not allow content created by ChatGPT while helping other people. You may still share its content, when you are not helping somebody and are not looking to deceive others, for example when discussing ChatGPT and its technology.
From An unknown user
Itsurran
ItsurranOP13mo ago
Holy, actually crazy. But im understanding it more now tbh Its just as you said here he showed the exact way
dan1st
dan1st13mo ago
I think it's important to understand these issues
Itsurran
ItsurranOP13mo ago
So if i take an example i have right now an cors policy blocked to this Access to XMLHttpRequest at 'http://localhost:8080/api/v1/auth/logout' from origin 'http://localhost:5173' has been blocked by CORS policy: if i fix this, for example evil.com can se the response correct?
dan1st
dan1st13mo ago
you can configure the headers so that only localhost:5173 can do it like that
Itsurran
ItsurranOP13mo ago
Should i have a CorsFilter so i can have more controll over my cors configurations something like
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("http://localhost:5173"); // Adjust the origin as needed
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/api/v1/auth/**", config);
return new CorsFilter(source);
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("http://localhost:5173"); // Adjust the origin as needed
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/api/v1/auth/**", config);
return new CorsFilter(source);
}
dan1st
dan1st13mo ago
yeah I'd do it like that
Itsurran
ItsurranOP13mo ago
Yep working now added a corsfilter damn im learning so much from you tbh i wanna keep this chat alive
dan1st
dan1st13mo ago
if it becomes dormant, you can just reopen it by sending a message in it the DM you get when it goes dormant (if enabled) should have a link to the post
Itsurran
ItsurranOP13mo ago
Yes sir, hope you don't mind me being annoying and asking 500 questions. Btw i have never handled a user avatar before, any suggestions how i should do that? im thinking of integrating so a user can have a profile image
dan1st
dan1st13mo ago
that's how you are learning not really - I would store the file on some dusk and store the name/identifier in a DB
JavaBot
JavaBot13mo ago
💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.
Itsurran
ItsurranOP13mo ago
Hi @dan1st | Daniel, i followed this post https://medium.com/@mertcakmak2/object-storage-with-spring-boot-and-aws-s3-64448c91018f And its working perfectly but how can i assoicate a uploaded picture to a user id so for exampel you are authenticated and you want a profile image so you upload it and its attached to your account.
Medium
Object Storage with Spring Boot and AWS S3
Hi, I will discuss AWS S3 in this article and demonstrate its usage in Spring Boot.
Itsurran
ItsurranOP13mo ago
Sorry this one i meant
JavaBot
JavaBot13mo ago
💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.
Itsurran
ItsurranOP13mo ago
Hi @dan1st | Daniel I have these error when running my application, i also debugged my application and it said application running. Can this be wrong with my dependency?
No description
No description
dan1st
dan1st13mo ago
Can you show your build configuration file? and please as text and not using images it looks like you might have version conflicts e.g. mixing Spring 5 and Spring 6
Itsurran
ItsurranOP13mo ago
ah ok sorry i forget everything will bare it in mind
package com.Nem.demo;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class NemBackendApplication {

public static void main(String[] args) {
SpringApplication.run(NemBackendApplication.class, args);
}



}
package com.Nem.demo;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class NemBackendApplication {

public static void main(String[] args) {
SpringApplication.run(NemBackendApplication.class, args);
}



}
Itsurran
ItsurranOP13mo ago
Itsurran
ItsurranOP13mo ago
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.Nem</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Nem-backend</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>s3</artifactId>
<version>2.23.19</version> <!-- Replace '2.x.x' with the version you want to use -->
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
<version>3.3.3.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>

</project>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.Nem</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Nem-backend</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>s3</artifactId>
<version>2.23.19</version> <!-- Replace '2.x.x' with the version you want to use -->
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
<version>3.3.3.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>

</project>
dependency
dan1st
dan1st13mo ago
you are using Spring Boot 3.2.2
tjoener
tjoener13mo ago
Too many versions
dan1st
dan1st13mo ago
Why are you using 3.3.3.RELEASE for spring-data-rest-webmvc?
Itsurran
ItsurranOP13mo ago
yh fixed it
dan1st
dan1st13mo ago
I think that would need 6.x
Itsurran
ItsurranOP13mo ago
i added a dependency before to use rest
dan1st
dan1st13mo ago
most of them are not managed by Spring
tjoener
tjoener13mo ago
spring-data-rest-webmvc definitely is
dan1st
dan1st13mo ago
yes I already mentioned that Spring Data 3 is ancient
Itsurran
ItsurranOP13mo ago
Hi, i added this code
@PostMapping(path = "/upload/profile-image", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
public String uploadProfileImage(@RequestParam("file") MultipartFile file, @RequestParam("userId") UUID id) throws IOException {

String imageUrl = s3Service.uploadFile("profile-images/" + id + "/" + file.getOriginalFilename(), file);

userService.updateProfileImageUrl(id, imageUrl);


return "Profile image uploaded successfully";
}
@PostMapping(path = "/upload/profile-image", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
public String uploadProfileImage(@RequestParam("file") MultipartFile file, @RequestParam("userId") UUID id) throws IOException {

String imageUrl = s3Service.uploadFile("profile-images/" + id + "/" + file.getOriginalFilename(), file);

userService.updateProfileImageUrl(id, imageUrl);


return "Profile image uploaded successfully";
}
and in my UserService
public void updateProfileImageUrl(UUID userId, String imageUrl) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new IllegalArgumentException("User not found with id: " + userId));
user.setImageUrl(imageUrl);
userRepository.save(user);
}
public void updateProfileImageUrl(UUID userId, String imageUrl) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new IllegalArgumentException("User not found with id: " + userId));
user.setImageUrl(imageUrl);
userRepository.save(user);
}
when im hitting the endpoint im getting access denied and im authenticated already here is the console
Itsurran
ItsurranOP13mo ago
When i hit this endpoint
@PostMapping(path = "/upload", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
s3Service.uploadFile(file.getOriginalFilename(), file);
return "File uploaded";
}
@PostMapping(path = "/upload", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
s3Service.uploadFile(file.getOriginalFilename(), file);
return "File uploaded";
}
without a user id it works to send it to the s3 bucket noticed this 2024-02-08T19:27:21.148+01:00 WARN 23468 --- [nio-8080-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required request parameter 'user_id' for method parameter type UUID is not present]
dan1st
dan1st13mo ago
So people can just change the profile picture of other users?
Itsurran
ItsurranOP13mo ago
What do you mean?
dan1st
dan1st13mo ago
the client can send whatever they want in the id field and the server doesn't check it and happily sets the profile picture of that user
Itsurran
ItsurranOP13mo ago
How should i restrict it? that only a user can change their own image
dan1st
dan1st13mo ago
you have a JWT filter, right?
Itsurran
ItsurranOP13mo ago
yes sir oh maybe thats why i get also access denied
dan1st
dan1st13mo ago
that sets an Authentication object In the controller, you can add an Authentication parameter and not a parameter for the user id and just use the id of the current authentication
Itsurran
ItsurranOP13mo ago
Sorry i took a break, do you mean on my controller?
public String uploadProfileImage(@RequestParam("file") MultipartFile file, @RequestParam("userId") Authentication authentication) throws IOException
public String uploadProfileImage(@RequestParam("file") MultipartFile file, @RequestParam("userId") Authentication authentication) throws IOException
you mean like this? and
UUID userId = UUID.fromString(authentication.name());
UUID userId = UUID.fromString(authentication.name());
then
userService.updateProfileImageUrl(userId, imageUrl);
userService.updateProfileImageUrl(userId, imageUrl);
?
Itsurran
ItsurranOP13mo ago
if so, im getting
dan1st
dan1st13mo ago
without RequestParam
Itsurran
ItsurranOP13mo ago
Itsurran
ItsurranOP13mo ago
@PostMapping(path = "/upload/profile-image", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
public String uploadProfileImage(@RequestParam("file") MultipartFile file) throws IOException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UUID userId = UUID.fromString(authentication.getName());
String imageUrl = s3Service.uploadFile("profile-images/" + userId + "/" + file.getOriginalFilename(), file);
userService.updateProfileImageUrl(userId, imageUrl);
return "Profile image uploaded successfully";
}
@PostMapping(path = "/upload/profile-image", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
public String uploadProfileImage(@RequestParam("file") MultipartFile file) throws IOException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UUID userId = UUID.fromString(authentication.getName());
String imageUrl = s3Service.uploadFile("profile-images/" + userId + "/" + file.getOriginalFilename(), file);
userService.updateProfileImageUrl(userId, imageUrl);
return "Profile image uploaded successfully";
}
dan1st
dan1st13mo ago
authentication.getName() doesn't give you the id it gives you the username or email or whatever
dan1st
dan1st13mo ago
just don't treat it as a uuid Do you have a way to get a user by its email? use that
Itsurran
ItsurranOP13mo ago
you mean in my repo? Optional<User> findByEmail(String email);
dan1st
dan1st13mo ago
yes
Itsurran
ItsurranOP13mo ago
@PostMapping(path = "/upload/profile-image", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
public String uploadProfileImage(@RequestParam("file") MultipartFile file) throws IOException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

String userEmail = authentication.getName();
Optional<User> optionalUser = userRepository.findByEmail(userEmail);

if (optionalUser.isPresent()) {
User user = optionalUser.get();
UUID userId = user.getId();
String imageUrl = s3Service.uploadFile("profile-images/" + userId + "/" + file.getOriginalFilename(), file);
userService.updateProfileImageUrl(userId, imageUrl);
return "Profile image uploaded successfully";
} else {
return "User not found";
}
}
@PostMapping(path = "/upload/profile-image", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
public String uploadProfileImage(@RequestParam("file") MultipartFile file) throws IOException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

String userEmail = authentication.getName();
Optional<User> optionalUser = userRepository.findByEmail(userEmail);

if (optionalUser.isPresent()) {
User user = optionalUser.get();
UUID userId = user.getId();
String imageUrl = s3Service.uploadFile("profile-images/" + userId + "/" + file.getOriginalFilename(), file);
userService.updateProfileImageUrl(userId, imageUrl);
return "Profile image uploaded successfully";
} else {
return "User not found";
}
}
did this and i get user not found in my postman 200ok user not found
dan1st
dan1st13mo ago
can you show your jwt filter?
Itsurran
ItsurranOP13mo ago
package com.Nem.demo.config;

import com.Nem.demo.token.TokenRepository;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

private final JwtService jwtService;

private final UserDetailsService userDetailsService;

private final TokenRepository tokenRepository;

@Override
protected void doFilterInternal
(@NonNull HttpServletRequest request,
@NonNull HttpServletResponse response,
@NonNull FilterChain filterChain)
throws ServletException, IOException {
final String authHeader = request.getHeader("Authorization");
final String jwt;
final String userEmail;
if (authHeader == null || !authHeader.startsWith(("Bearer "))) {
filterChain.doFilter(request, response);
return;
}
jwt = authHeader.substring(7);
userEmail = jwtService.extractUsername(jwt);
if (userEmail != null && SecurityContextHolder.getContext().getAuthentication() == null){
UserDetails userDetails = this.userDetailsService.loadUserByUsername(userEmail);
var isTokenValid = tokenRepository.findByToken(jwt)
.map(t -> !t.isExpired() && !t.isRevoked())
.orElse(false);
if(jwtService.isTokenValid(jwt, userDetails) && isTokenValid){
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
userDetails,
null,
userDetails.getAuthorities()
);
authToken.setDetails(
new WebAuthenticationDetailsSource().buildDetails(request)
);
SecurityContextHolder.getContext().setAuthentication(authToken);
}
}
filterChain.doFilter(request, response);
}

}
package com.Nem.demo.config;

import com.Nem.demo.token.TokenRepository;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

private final JwtService jwtService;

private final UserDetailsService userDetailsService;

private final TokenRepository tokenRepository;

@Override
protected void doFilterInternal
(@NonNull HttpServletRequest request,
@NonNull HttpServletResponse response,
@NonNull FilterChain filterChain)
throws ServletException, IOException {
final String authHeader = request.getHeader("Authorization");
final String jwt;
final String userEmail;
if (authHeader == null || !authHeader.startsWith(("Bearer "))) {
filterChain.doFilter(request, response);
return;
}
jwt = authHeader.substring(7);
userEmail = jwtService.extractUsername(jwt);
if (userEmail != null && SecurityContextHolder.getContext().getAuthentication() == null){
UserDetails userDetails = this.userDetailsService.loadUserByUsername(userEmail);
var isTokenValid = tokenRepository.findByToken(jwt)
.map(t -> !t.isExpired() && !t.isRevoked())
.orElse(false);
if(jwtService.isTokenValid(jwt, userDetails) && isTokenValid){
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
userDetails,
null,
userDetails.getAuthorities()
);
authToken.setDetails(
new WebAuthenticationDetailsSource().buildDetails(request)
);
SecurityContextHolder.getContext().setAuthentication(authToken);
}
}
filterChain.doFilter(request, response);
}

}
i have userEmail as my "username" or whatever
dan1st
dan1st13mo ago
looks like it I guess use that?
Itsurran
ItsurranOP13mo ago
So this is my current endpoint
@PostMapping(path = "/upload/profile-image", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
public String uploadProfileImage(@RequestParam("file") MultipartFile file) throws IOException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UUID userId = UUID.fromString(authentication.getName());
String imageUrl = s3Service.uploadFile("profile-images/" + userId + "/" + file.getOriginalFilename(), file);
userService.updateProfileImageUrl(userId, imageUrl);
return "Profile image uploaded successfully";
}
@PostMapping(path = "/upload/profile-image", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
public String uploadProfileImage(@RequestParam("file") MultipartFile file) throws IOException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UUID userId = UUID.fromString(authentication.getName());
String imageUrl = s3Service.uploadFile("profile-images/" + userId + "/" + file.getOriginalFilename(), file);
userService.updateProfileImageUrl(userId, imageUrl);
return "Profile image uploaded successfully";
}
and its wrong cause im not getting the userEmail like you said but how can i get it from there? i need a request.setAttribute("userEmail", userEmail); in my jwt filter? and then getattribute?
dan1st
dan1st13mo ago
maybe something in your user repo like getByUserName you could try that as well or saving the user id as an attribute
Itsurran
ItsurranOP13mo ago
Okej so i added this
i need a request.setAttribute("userEmail", userEmail);
i need a request.setAttribute("userEmail", userEmail);
to my filter then in my service i added
public User getUserByEmail(String email) {
return userRepository.findByEmail(email).orElse(null);
}
public User getUserByEmail(String email) {
return userRepository.findByEmail(email).orElse(null);
}
and my endpoint
@PostMapping(path = "/upload/profile-image", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
public String uploadProfileImage(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
String userEmail = (String) request.getAttribute("userEmail");
if (userEmail != null) {

User user = userService.getUserByEmail(userEmail);
if (user != null) {
UUID userId = user.getId();
String imageUrl = s3Service.uploadFile("profile-images/" + userId + "/" + file.getOriginalFilename(), file);
userService.updateProfileImageUrl(userId, imageUrl);
return "Profile image uploaded successfully";
} else {
return "User not found";
}
} else {
return "Unauthorized";
}
}
@PostMapping(path = "/upload/profile-image", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
public String uploadProfileImage(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
String userEmail = (String) request.getAttribute("userEmail");
if (userEmail != null) {

User user = userService.getUserByEmail(userEmail);
if (user != null) {
UUID userId = user.getId();
String imageUrl = s3Service.uploadFile("profile-images/" + userId + "/" + file.getOriginalFilename(), file);
userService.updateProfileImageUrl(userId, imageUrl);
return "Profile image uploaded successfully";
} else {
return "User not found";
}
} else {
return "Unauthorized";
}
}
and the result
No description
Itsurran
ItsurranOP13mo ago
Thank you so much!
JavaBot
JavaBot13mo ago
If you are finished with your post, please close it. If you are not, please ignore this message. Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.
Itsurran
ItsurranOP13mo ago
i have been on this profileimage for almost 2 days... Just curiousity question, so when a user wants to upload another image does that hit another endpoint or the same? Or should I have update endpoint Like they want to change their current image Not add another one
JavaBot
JavaBot13mo ago
💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.

Did you find this page helpful?