JWT Authentication with SpringBoot

So it gives me a successful token, but when I use it for authorized pages, I get a 403, Access denied on the backend
105 Replies
JavaBot
JavaBot4mo ago
This post has been reserved for your question.
Hey @Rag...JN 🌌 🦡 👽 💰! 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.
Rag...JN 🌌 🦡 👽 💰 🐊
This is the tutorial I followed I want to know where am I getting the Access Denied
dan1st
dan1st4mo ago
enable TRACE logs for Spring Security
dan1st
dan1st4mo ago
Can you show the full console output related to the request as text?
Rag...JN 🌌 🦡 👽 💰 🐊
Full error message?
dan1st
dan1st4mo ago
seems like you don't have the necessary authorities for the requests and also other logs in a codeblock preferably
Rag...JN 🌌 🦡 👽 💰 🐊
This is the secruity filter
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth.requestMatchers("/auth/welcome", "/auth/addNewUser", "/auth/generateToken").permitAll())
.authorizeHttpRequests(auth -> auth.requestMatchers("/auth/user/**").authenticated())
.authorizeHttpRequests(auth -> auth.requestMatchers("/auth/admin/**").authenticated())
.sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authenticationProvider(authenticationProvider())
.addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth.requestMatchers("/auth/welcome", "/auth/addNewUser", "/auth/generateToken").permitAll())
.authorizeHttpRequests(auth -> auth.requestMatchers("/auth/user/**").authenticated())
.authorizeHttpRequests(auth -> auth.requestMatchers("/auth/admin/**").authenticated())
.sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authenticationProvider(authenticationProvider())
.addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}
dan1st
dan1st4mo ago
your authFilter is probably relevant as well is that one called for the request?
Rag...JN 🌌 🦡 👽 💰 🐊
the authFilter is JwtAuthFilter
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
@Autowired
private JwtAuthFilter authFilter;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
@Autowired
private JwtAuthFilter authFilter;

@Component
public class JwtAuthFilter extends OncePerRequestFilter {
@Autowired
private JwtService jwtService;

@Autowired
private UserInfoService userDetailsService;

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String authHeader = request.getHeader("Authorization");
String token = null;
String username = null;
if(authHeader !=null && authHeader.startsWith("Bearer ")) {
token = authHeader.substring(7);
username = jwtService.getUsernameFromToken(token);
}

if(username !=null && SecurityContextHolder.getContext().getAuthentication()==null) {
UserDetails userDetails = userDetailsService.loadUserByUsername(username);


if(jwtService.validateToken(token, username)) {
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authToken);
}
}
filterChain.doFilter(request, response);

}


}
@Component
public class JwtAuthFilter extends OncePerRequestFilter {
@Autowired
private JwtService jwtService;

@Autowired
private UserInfoService userDetailsService;

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String authHeader = request.getHeader("Authorization");
String token = null;
String username = null;
if(authHeader !=null && authHeader.startsWith("Bearer ")) {
token = authHeader.substring(7);
username = jwtService.getUsernameFromToken(token);
}

if(username !=null && SecurityContextHolder.getContext().getAuthentication()==null) {
UserDetails userDetails = userDetailsService.loadUserByUsername(username);


if(jwtService.validateToken(token, username)) {
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authToken);
}
}
filterChain.doFilter(request, response);

}


}
Rag...JN 🌌 🦡 👽 💰 🐊
Hmm this is unreadable also it says Pre-authenticated entry point called. Rejecting access let me check about it
dan1st
dan1st4mo ago
try debugging that filter what happens?
Set SecurityContextHolder to AnonymousAuthenticationToken
Check what validateToken does Does it return true? and what does getAuthentication() return?
Rag...JN 🌌 🦡 👽 💰 🐊
I tried to put a Sout but it's not printing out
dan1st
dan1st4mo ago
the filter is called according to the logs Did you restart the application after adding the System.out.println? Did you try using an actual debugger?
Rag...JN 🌌 🦡 👽 💰 🐊
no let me try now I added a break point
dan1st
dan1st4mo ago
make sure to run it in debug mode
Rag...JN 🌌 🦡 👽 💰 🐊
yah it prints out the outputs I am going to use debugger now
No description
Rag...JN 🌌 🦡 👽 💰 🐊
This is what the debugger environment currently look like and when I make a request I see no changes
No description
Rag...JN 🌌 🦡 👽 💰 🐊
how do I step into?
dan1st
dan1st4mo ago
Can you set a breakpoint at the beginning of doFilterInternal? F5 step into, F6 step over, F8 resume
Rag...JN 🌌 🦡 👽 💰 🐊
let me try I did and made a request still the step into is unclickable
dan1st
dan1st4mo ago
you first need to be stepping through your code which happens when hitting a breakpoint
Rag...JN 🌌 🦡 👽 💰 🐊
I set a breakpoint right then I made a request in postman, and the doFilterInternal is being called. so that means it should be hitting the breakpoint
dan1st
dan1st4mo ago
If the line doesn't turn green, it isn't hit Also why are there these weird lines in your breakpoints? Are they disabled?
Rag...JN 🌌 🦡 👽 💰 🐊
which weird lines?
No description
dan1st
dan1st4mo ago
on the left bar at the breakpoint symbols there are two diagonal lines over the symbol try right-clicking on the breakpoint
Rag...JN 🌌 🦡 👽 💰 🐊
what am I doing wrong
dan1st
dan1st4mo ago
breakpoint properties doesn't seem disabled
Rag...JN 🌌 🦡 👽 💰 🐊
no trigger breakpoint is the issue?
No description
dan1st
dan1st4mo ago
it shouldn't be a trigger point actually do you have other breakpoints? or other trigger points?
dan1st
dan1st4mo ago
Can you show the breakpoints view? trigger point means "no breakpoints are active before I am hit"
Rag...JN 🌌 🦡 👽 💰 🐊
where this can be found?
dan1st
dan1st4mo ago
eiter on the top right in the debug perspective or Window > Show View > Others > Breakpoints or Ctrl+3 > Breakpoints
Rag...JN 🌌 🦡 👽 💰 🐊
wow ok there are 3 break points the language is messed up for some reason
No description
dan1st
dan1st4mo ago
remove all with the double x symbol for example I think it's the font being weird
Rag...JN 🌌 🦡 👽 💰 🐊
so now try again with the new break point on doFilterInternal?
dan1st
dan1st4mo ago
now add the relevant breakpoint again yes oh
dan1st
dan1st4mo ago
Stack Overflow
Meaning of crossed out breakpoint in Eclipse
what is the meaning of this break point icon? Why is it crossed out?
dan1st
dan1st4mo ago
you enabled "Skip all breakpoints" on the top right, there is a selected icon with a crossed out breakpoint symbol
dan1st
dan1st4mo ago
Stack Overflow
What different breakpoint icons mean in Eclipse?
When working with breakpoints in Eclipse I sometimes notice that they have different icons / annotations (markers on left sidebar). Sometimes it's just a blue ball, sometimes it has a checkmark on ...
Rag...JN 🌌 🦡 👽 💰 🐊
wow finally
No description
Rag...JN 🌌 🦡 👽 💰 🐊
Thank you so much
JavaBot
JavaBot4mo 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.
Rag...JN 🌌 🦡 👽 💰 🐊
I got got the error before StandardHostValve
No description
Rag...JN 🌌 🦡 👽 💰 🐊
it breaks down here
No description
dan1st
dan1st4mo ago
What happens in the filter?
Rag...JN 🌌 🦡 👽 💰 🐊
This is where it starts to go inside and breaks
No description
dan1st
dan1st4mo ago
in the getUsername? or in validateToken?
dan1st
dan1st4mo ago
Can you show the full line as text? Which method fails?
Rag...JN 🌌 🦡 👽 💰 🐊
oh wait this time it completed the full filter method
dan1st
dan1st4mo ago
in what order? Did it enter the if?
Rag...JN 🌌 🦡 👽 💰 🐊
but there are more chains
dan1st
dan1st4mo ago
yes but I want to know about this filter
Rag...JN 🌌 🦡 👽 💰 🐊
I mean what you see on the debug list
dan1st
dan1st4mo ago
no I can't I want to know what is executed after each other and I want to know the value of authToken
Rag...JN 🌌 🦡 👽 💰 🐊
oh ok let me see btw this is the recording
Rag...JN 🌌 🦡 👽 💰 🐊
look at my debug skills So the problem is not in this JwtAuthFilter The filter passes the request and response to the next Filter
dan1st
dan1st4mo ago
.
Rag...JN 🌌 🦡 👽 💰 🐊
it should be showing at variables section right?
No description
Rag...JN 🌌 🦡 👽 💰 🐊
I have to fix this font issue
dan1st
dan1st4mo ago
Window>Preferences type "font" in the search I guess it's the dialog font also you can hover over the variable
dan1st
dan1st4mo ago
Can you move your filter after AnonymousAuthenticationFilter?
Rag...JN 🌌 🦡 👽 💰 🐊
somewhere here right?
No description
dan1st
dan1st4mo ago
instead of addFilterBefore, you do addFilterAfter and instead of UsernamePasswordAuthenticationFilter, you do AnonymousAuthenticationFilter
Rag...JN 🌌 🦡 👽 💰 🐊
So no need to define the UsernamePasswordAutehticationFilter?
Rag...JN 🌌 🦡 👽 💰 🐊
I just comment it out
No description
dan1st
dan1st4mo ago
What happens with that? btw regarding debugging: You can press F8 to resume
Rag...JN 🌌 🦡 👽 💰 🐊
you mean new results? yah let me run
dan1st
dan1st4mo ago
yep
Rag...JN 🌌 🦡 👽 💰 🐊
It broke down at OncePerRequestFilter it doesn't pass the filter it looks like it and also it doesn't go inside the if statement
Rag...JN 🌌 🦡 👽 💰 🐊
it's not going insde the line 41's if statement
No description
dan1st
dan1st4mo ago
ah right because getAuthentication isn't null any more try changing iz to enter the if if getAuthentication().isAnonymous() is true
Rag...JN 🌌 🦡 👽 💰 🐊
it doesn't have a isAnonymous method SecurityContextHolder.getContext().getAuthentication()
dan1st
dan1st4mo ago
check for isAuthenticated() being false if it is, still enter the if instead of isAnonymous being true
Rag...JN 🌌 🦡 👽 💰 🐊
yah it is being true
No description
dan1st
dan1st4mo ago
As I said, just add that || ...isAnonymous()
JavaBot
JavaBot4mo 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.
Rag...JN 🌌 🦡 👽 💰 🐊
ok do you know all of these?
dan1st
dan1st4mo ago
all of what?
Rag...JN 🌌 🦡 👽 💰 🐊
isAnonymous and stuff Because I have no idea about it
dan1st
dan1st4mo ago
I just used Spring a lot so I know what's there but as you saw with isAuthenticated, I don't know all names by heart
Rag...JN 🌌 🦡 👽 💰 🐊
how do I properly learn authentication and authorization I followed online articles came up with errors here In SpringBoot I have done JWT authentication in Java Jersey framework before but this is complicated
Rag...JN 🌌 🦡 👽 💰 🐊
GeeksforGeeks
Spring Boot 3.0 - JWT Authentication with Spring Security using MyS...
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
From An unknown user
From An unknown user
From An unknown user
From An unknown user
dan1st
dan1st4mo ago
Getting Started | Securing a Web Application
Getting Started | Securing a Web Application
Learn how to protect your web application with Spring Security.
Rag...JN 🌌 🦡 👽 💰 🐊
yah this is easy it's form login inside the application
Rag...JN 🌌 🦡 👽 💰 🐊
none of them talks about API (React as a frontned) with JWT authentication they are oauth 2.0
dan1st
dan1st4mo ago
The OAuth2 thing has some jwt stuff in it Also what I told you about isn't even that specific to JWTs
Rag...JN 🌌 🦡 👽 💰 🐊
ok I'll try again I am reading Java basic architecture rn 😆
JavaBot
JavaBot4mo 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.
💤 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.
Want results from more Discord servers?
Add your server