-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
12044 - Testing the application #21
Comments
they said to rerun the spring boot app just to make sure so lets rerun that
|
they gonna use postman to test the application, well use thunderclient |
had a error when running, basically wrong Date import. heres the corrected code for JwtUtils.java
package com.nellyxinwei.backend.config;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
@Component
public class JwtUtils {
private String jwtSigningKey = "secret";
public String extractUsername(String token) {
return extractClaim(token, Claims::getSubject);
}
public Date extractExpiration(String token) {
return extractClaim(token, Claims::getExpiration);
}
public boolean hasClaim(String token, String claimName) {
final Claims claims = extractAllClaims(token);
return claims.get(claimName) != null;
}
public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
final Claims claims = extractAllClaims(token);
return claimsResolver.apply(claims);
}
private Claims extractAllClaims(String token) {
return Jwts.parser().setSigningKey(jwtSigningKey).parseClaimsJws(token).getBody();
}
private Boolean isTokenExpired(String token) {
return extractExpiration(token).before(new Date());
}
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
return createToken(claims, userDetails);
}
public String generateToken(UserDetails userDetails, Map<String, Object> claims) {
return createToken(claims, jwtSigningKey);
}
private String createToken(Map<String, Object> claims, String subject) {
return Jwts.builder().setClaims(claims)
.setSubject(userDetails.getUsername())
.claim("authorities", userDetails.getAuthorities())
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(24)))
.signWith(SignatureAlgorithm.HS256, jwtSigningKey).compact();
}
public Boolean isTokenValid(String token, UserDetails userDetails) {
final String username = extractUsername(token);
return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
}
} |
now lets proceed with testing
|
ugh they added more stuff to the SecurityConfig.java in the background (not recorded in the vid) cuz they forgot something
package com.nellyxinwei.backend.config;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.apache.tomcat.jni.User;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
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.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import com.nellyxinwei.backend.dao.UserDao;
import io.jsonwebtoken.lang.Arrays;
import lombok.RequiredArgsConstructor;
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
private final JwtAthFilter jwtAthFilter;
private final UserDao userDao;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authenticationProvider(authenticationProvider())
.addFilterBefore(jwtAthFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
@Bean
public AuthenticationProvider authenticationProvider() {
final DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService());
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
return config.getAuthenticationManager();
}
@Bean
public PasswordEncoder passwordEncoder() {
// return new BCryptPasswordEncoder();
return NoOpPasswordEncoder.getInstance();
}
@Bean
public UserDetailsService userDetailsService() {
return new UserDetailsService() {
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
return userDao.findUserByEmail(email);
}
};
}
} they forgot the .csrf().disable inside the securityfilterchain bean |
ok we have more edits again for SecurityConfig.json
package com.nellyxinwei.backend.config;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.apache.tomcat.jni.User;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
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.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import com.nellyxinwei.backend.dao.UserDao;
import io.jsonwebtoken.lang.Arrays;
import lombok.RequiredArgsConstructor;
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
private final JwtAthFilter jwtAthFilter;
private final UserDao userDao;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/**/auth/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authenticationProvider(authenticationProvider())
.addFilterBefore(jwtAthFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
@Bean
public AuthenticationProvider authenticationProvider() {
final DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService());
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
return config.getAuthenticationManager();
}
@Bean
public PasswordEncoder passwordEncoder() {
// return new BCryptPasswordEncoder();
return NoOpPasswordEncoder.getInstance();
}
@Bean
public UserDetailsService userDetailsService() {
return new UserDetailsService() {
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
return userDao.findUserByEmail(email);
}
};
}
} also in the same bean, they added antmatchers and permitall() |
rerun the spring boot app
|
|
idk i followed everything the best i can but it dont work |
it was already confusing when they were doing things in the background or copy pasted something without the link. also no source code so idk |
so i decided to go through my own deviation from the course with their JwtUtils.java. I went back to these links:
this link especially helped me fix the JwtUtils.java and the AUTHORIZATION theng fixed it to just "Authorization" with the help of this link: i then rerun the spring boot application as my editor doesnt give anymore errors, tested the request again then boom it worked and gave me a generated JWT token. ill paste here all my files with the fixes. this has been so kinda annoying i swear but anyways thanks to the people who provided this course learning. |
rerun the spring boot app
|
|
they showed in the course using this website: https://jwt.io
|
ok so compared to when they did the jwt.io theng, in my payload its missing the authorities array... |
ok i fixed it UGHHH 😒 now its also showing the authorities rerun the spring boot app
lets do the https://jwt.io again
|
now with our bearer jwt token, lets try making the requests to greetingscontroller.
|
nice, it all worked out in the end 😌 😒 had to go through a lot of deviations and doing my own stuff still. |
anyways. ill push up the correct codes instead of posting them each here. this project is done. let us now conclude our session |
Timestamp: (12044) 12628 / 12948
The text was updated successfully, but these errors were encountered: