Skip to content

Commit

Permalink
self review
Browse files Browse the repository at this point in the history
  • Loading branch information
bhtibrewal committed Mar 3, 2024
1 parent d5d7060 commit 222919c
Show file tree
Hide file tree
Showing 15 changed files with 51 additions and 170 deletions.
4 changes: 4 additions & 0 deletions skill-tree/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,8 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

<!-- io.jsonwebtoken -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
Expand All @@ -111,6 +113,8 @@
<artifactId>jjwt-jackson</artifactId>
<version>${io.jsonwebtoken.version}</version>
</dependency>
<!-- io.jsonwebtoken -->

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,4 @@ public void commence(HttpServletRequest request, HttpServletResponse response, A
this.resolver.resolveException(request, response,null, authException);
}

// @ExceptionHandler(value = {AccessDeniedException.class})
// public void commence(HttpServletRequest request, HttpServletResponse response,
// AccessDeniedException accessDeniedException) throws IOException {
// // 403
// response.sendError(HttpServletResponse.SC_FORBIDDEN, "Authorization Failed : " + accessDeniedException.getMessage());
// }

}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
Expand All @@ -28,25 +29,25 @@ public class SecurityConfig {

private final AuthEntryPoint authEntryPoint;
private final CustomAccessDeniedHandler accessDeniedHandler;
private final String[] roles = Arrays.stream(UserRole.values()).map(role -> role.label).toArray(String[]::new);
private final String[] roles = Arrays.stream(UserRole.values()).map(role -> role.label).toArray(String[]::new);


public SecurityConfig(AuthEntryPoint authEntryPoint, CustomAccessDeniedHandler accessDeniedHandler) {
this.authEntryPoint = authEntryPoint;
this.accessDeniedHandler = accessDeniedHandler;
}

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable)
.cors(httpSecurityCorsConfigurer -> httpSecurityCorsConfigurer.configurationSource(corsConfigurationSource()))
.authorizeHttpRequests(auth->auth
.requestMatchers( "/v1/endorsements/status").hasAuthority(UserRole.SUPERUSER.label)
.requestMatchers("/v1/endorsements/**").hasAnyAuthority(roles)
.anyRequest().authenticated())

.exceptionHandling(ex->ex.accessDeniedHandler(this.accessDeniedHandler).authenticationEntryPoint(this.authEntryPoint))
.sessionManagement(session->session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

.cors(httpSecurityCorsConfigurer -> httpSecurityCorsConfigurer.configurationSource(corsConfigurationSource()))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/v1/endorsements/status").hasAuthority(UserRole.SUPERUSER.label)
.requestMatchers("/v1/endorsements/**").hasAnyAuthority(roles)
.anyRequest().authenticated())
.exceptionHandling(ex -> ex.accessDeniedHandler(this.accessDeniedHandler).authenticationEntryPoint(this.authEntryPoint))
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
// http.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
return http.build();
}
Expand All @@ -63,8 +64,9 @@ public CorsConfigurationSource corsConfigurationSource() {
source.registerCorsConfiguration("/**", configuration);
return source;
}

@Bean
public JWTAuthenticationFilter jwtAuthenticationFilter(){
public JWTAuthenticationFilter jwtAuthenticationFilter() {
return new JWTAuthenticationFilter();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ public ResponseEntity<GenericResponse<EndorsementDTO>> postEndorsement(@RequestB

}

// NOTE: dummy endpoint added to check super-user authorisation
@PostMapping (value="/status")
public String updateEndorsementStatus(){
return "This is a Super user only route";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,24 +27,20 @@ public class JWTAuthenticationFilter extends OncePerRequestFilter {
@Autowired
private JWTUtils jwtUtils;


@Override
public void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain)
throws ServletException, IOException {
public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

String token = getJWTFromRequest(request);

try {
if (StringUtils.hasText(token) && jwtUtils.validateToken(token)) {
String rdsUserId = jwtUtils.getRDSUserId(token);
String role= jwtUtils.getUserRole(token);
String rdsUserId = jwtUtils.getRDSUserId(token);
String role = jwtUtils.getUserRole(token);


UserAuthenticationToken authentication = new UserAuthenticationToken(role, rdsUserId);
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
UserAuthenticationToken authentication = new UserAuthenticationToken(role, rdsUserId);
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);

}
} catch (Exception e) {
Expand All @@ -56,12 +52,11 @@ public void doFilterInternal(HttpServletRequest request,

public String getJWTFromRequest(HttpServletRequest request) {

/* */
/* check for cookie */
Cookie RDScookie = WebUtils.getCookie(request, cookieName);
if(RDScookie != null)
return RDScookie.getValue();
if (RDScookie != null) return RDScookie.getValue();

/* */
/* extract token from header */
String bearerToken = request.getHeader("Authorization");
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7);
Expand Down
3 changes: 2 additions & 1 deletion skill-tree/src/main/java/com/RDS/skilltree/User/UserDRO.java
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ public static UserModel compareAndUpdateModel(UserModel user, UserDRO userDRO) {
if (userDRO.getRole() != null) {
user.setRole(user.getRole());
}

user.setUpdatedAt(Instant.now());
user.setUpdatedBy(user);
return user;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,8 @@
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import jakarta.persistence.*;
import lombok.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.net.URL;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.UUID;

Expand All @@ -24,7 +19,7 @@
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "Users")
public class UserModel extends TrackedProperties {
public class UserModel extends TrackedProperties {
@Id
@GeneratedValue
@Column(name = "id", columnDefinition = "BINARY(16)")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@
public enum UserRole {
USER("user"),
MEMBER("member"),
SUPERUSER("super_user"),
MAVEN("maven");
SUPERUSER("super_user");

public final String label;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public ResponseEntity<GenericResponse<Object>> handleNoEntityException(NoEntityE

@ExceptionHandler({AuthenticationException.class, InsufficientAuthenticationException.class})
public ResponseEntity<GenericResponse<Object>> handleInvalidBearerTokenException(Exception ex) {
return ResponseEntity.status( HttpStatus.UNAUTHORIZED).body(new GenericResponse<>(null, "The access token provided is expired, revoked, malformed, or invalid for other reasons."+ ex.getMessage()));
return ResponseEntity.status( HttpStatus.UNAUTHORIZED).body(new GenericResponse<>(null, "The access token provided is expired, revoked, malformed, or invalid for other reasons."));
}
@ExceptionHandler({AccessDeniedException.class})
public ResponseEntity<GenericResponse<Object>> handleAccessDeniedException(AccessDeniedException ex) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,13 +75,9 @@ public String getUserRole(String token) throws Exception {
return claims.get("role", String.class);
}

public boolean validateToken(String token) throws Exception { //TODO check for the case where token is expired
try {
return (!isTokenExpired(token));
public boolean validateToken(String token) throws Exception {

} catch (Exception e) {
throw new AuthenticationCredentialsNotFoundException("Invalid JWT");
}
return (!isTokenExpired(token));
}

}
1 change: 0 additions & 1 deletion skill-tree/src/main/resources/application-test.properties

This file was deleted.

2 changes: 1 addition & 1 deletion skill-tree/src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ API_V1_PREFIX=/api/v1
spring.datasource.version=8.1.0
management.endpoints.web.exposure.include=health,info,metrics
logging.level.root=ERROR
cookieName=rds-session-v2-development
cookieName={COOKIE_NAME:rds-session-v2-development}
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,14 @@ public class SecurityContextIntegrationTest extends TestContainerManager {
public void testTokenIsNotPresent() {

Response response = given().get("/v1/health");
response.then().statusCode(401).body("message", equalTo("The access token provided is expired, revoked, malformed, or invalid for other reasons.Full authentication is required to access this resource"));
response.then().statusCode(401).body("message", equalTo("The access token provided is expired, revoked, malformed, or invalid for other reasons."));
}

@Test
public void testInvalidToken() {

Response response = given().cookie("rds-session-v2", "invalidtoken").get("/v1/health");
response.then().statusCode(401).body("message", equalTo("The access token provided is expired, revoked, malformed, or invalid for other reasons.Full authentication is required to access this resource"));
response.then().statusCode(401).body("message", equalTo("The access token provided is expired, revoked, malformed, or invalid for other reasons."));
}

@Test
Expand Down

This file was deleted.

Loading

0 comments on commit 222919c

Please sign in to comment.