Skip to content
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

Programming exercises: Add tool token support #9408

Open
wants to merge 47 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
47 commits
Select commit Hold shift + click to select a range
5dec295
enable bearer authentication
janthoXO Oct 1, 2024
b447b28
Add re-key endpoint
janthoXO Oct 1, 2024
a3d0fbb
Implement rabbit feedback
janthoXO Oct 2, 2024
069f2eb
Merge branch 'feature/bearer-support' of github.com:ls1intum/Artemis …
janthoXO Oct 4, 2024
39e4bad
make token theia specific
janthoXO Oct 4, 2024
ddd8802
fix conversion from day to millis
janthoXO Oct 4, 2024
07afea2
only respond as cookie if asked for
janthoXO Oct 4, 2024
b59f8ad
fix class cast error for websockets
janthoXO Oct 5, 2024
896fd4c
let login return json with token
janthoXO Oct 7, 2024
2e247db
add server test for bearer token
janthoXO Nov 6, 2024
e8bde67
Merge branch 'develop' into feature/bearer-support
iyannsch Nov 7, 2024
c36c6ec
Merge branch 'develop' into feature/re-key
iyannsch Nov 7, 2024
8743e73
Merge branch 'feature/bearer-support' of github.com:ls1intum/Artemis …
iyannsch Nov 7, 2024
02e63b7
change theia token to general tool token endpoint
janthoXO Nov 8, 2024
44ca43c
Apply suggestions from code review
janthoXO Nov 8, 2024
6cab497
add tool token annotation
janthoXO Nov 9, 2024
e2bb2d0
Merge remote-tracking branch 'origin/feature/re-key' into feature/re-key
janthoXO Nov 9, 2024
6e61b26
move interceptor registration
janthoXO Nov 9, 2024
149a53a
add tool token option to login
janthoXO Nov 11, 2024
b0ed73d
change filter chain to only accept one auth method
janthoXO Nov 11, 2024
6b19a87
Merge remote-tracking branch 'origin/feature/bearer-support' into fea…
janthoXO Nov 11, 2024
8df1a6b
write filter a bit nicer
janthoXO Nov 11, 2024
7fe83a9
Merge branch 'feature/bearer-support' of github.com:ls1intum/Artemis …
janthoXO Nov 12, 2024
9f61018
annotate endpoints required by Scorpio
janthoXO Nov 12, 2024
5908f73
change bad request behaviour
janthoXO Nov 12, 2024
288a1eb
Merge branch 'develop' of github.com:ls1intum/Artemis into feature/be…
iyannsch Nov 18, 2024
81f4739
Merge branch 'develop' of github.com:ls1intum/Artemis into feature/re…
iyannsch Nov 18, 2024
7a69620
fix server tests
Nov 19, 2024
5803813
Merge remote-tracking branch 'origin/feature/re-key' into feature/re-key
Nov 19, 2024
1cf7281
Merge branch 'develop' of github.com:ls1intum/Artemis into feature/be…
Nov 19, 2024
4dabd91
Merge branch 'feature/bearer-support' of github.com:ls1intum/Artemis …
Nov 19, 2024
52b816b
Merge branch 'feature/bearer-support' of github.com:ls1intum/Artemis …
Nov 19, 2024
9ca745b
adjust tests
Nov 19, 2024
277f8b1
merge from bearer support
Nov 19, 2024
3e93d8c
include rabbit feedback
Nov 19, 2024
8715557
Merge branch 'feature/bearer-support' of github.com:ls1intum/Artemis …
Nov 19, 2024
ca0aa32
include test for allowedTools annotation
Nov 20, 2024
f2f2851
change from Date to ZonedDateTime
Nov 20, 2024
fe7af6d
use system.currenttimemillis instead of zonedtimedate
Nov 20, 2024
28d0c44
Merge branch 'develop' of github.com:ls1intum/Artemis into feature/re…
Nov 20, 2024
1b257ed
allow scorpio to get vcs access token
Nov 20, 2024
e57a661
allow login and logout with scorpio
Nov 26, 2024
7172f9c
Merge branch 'develop' of github.com:ls1intum/Artemis into feature/be…
iyannsch Nov 26, 2024
30a8652
Merge branch 'feature/bearer-support' into feature/re-key
iyannsch Nov 26, 2024
44489c3
allow scorpio to fetch feedback
janthoXO Dec 5, 2024
504b2d3
merge
Dec 9, 2024
02c62a5
Merge branch 'develop' into feature/re-key
janthoXO Dec 10, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import java.util.regex.Pattern;

import jakarta.annotation.Nullable;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.NotNull;

import org.slf4j.Logger;
Expand Down Expand Up @@ -52,7 +52,6 @@
import org.springframework.web.socket.server.HandshakeInterceptor;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;
import org.springframework.web.socket.sockjs.transport.handler.WebSocketTransportHandler;
import org.springframework.web.util.WebUtils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Iterators;
Expand Down Expand Up @@ -203,8 +202,7 @@ public boolean beforeHandshake(@NotNull ServerHttpRequest request, @NotNull Serv
@NotNull Map<String, Object> attributes) {
if (request instanceof ServletServerHttpRequest servletRequest) {
attributes.put(IP_ADDRESS, servletRequest.getRemoteAddress());
Cookie jwtCookie = WebUtils.getCookie(servletRequest.getServletRequest(), JWTFilter.JWT_COOKIE_NAME);
return JWTFilter.isJwtCookieValid(tokenProvider, jwtCookie);
return JWTFilter.extractValidJwt((HttpServletRequest) servletRequest, tokenProvider) != null;
}
return false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,17 @@ public ResponseCookie buildLoginCookie(boolean rememberMe) {
return buildJWTCookie(jwt, duration);
}

/**
* Builds the cookie with Theia flag
*
* @param duration the duration of the cookie and the jwt
janthoXO marked this conversation as resolved.
Show resolved Hide resolved
* @return the login ResponseCookie containing the JWT
*/
public ResponseCookie buildTheiaCookie(long duration) {
janthoXO marked this conversation as resolved.
Show resolved Hide resolved
String jwt = tokenProvider.createToken(SecurityContextHolder.getContext().getAuthentication(), duration, "THEIA");
return buildJWTCookie(jwt, Duration.of(duration, ChronoUnit.MILLIS));
}
janthoXO marked this conversation as resolved.
Show resolved Hide resolved

/**
* Builds the cookie containing the jwt for a logout and sets it in the response
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;

import org.springframework.lang.Nullable;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
Expand All @@ -31,26 +32,72 @@ public JWTFilter(TokenProvider tokenProvider) {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
Cookie jwtCookie = WebUtils.getCookie(httpServletRequest, JWT_COOKIE_NAME);
if (isJwtCookieValid(this.tokenProvider, jwtCookie)) {
Authentication authentication = this.tokenProvider.getAuthentication(jwtCookie.getValue());

// check if valid JWT token is in the cookie or in the Authorization header
// then proceed to do authentication with this token
String jwtToken = extractValidJwt(httpServletRequest, this.tokenProvider);
if (jwtToken != null) {
Authentication authentication = this.tokenProvider.getAuthentication(jwtToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
}

filterChain.doFilter(servletRequest, servletResponse);
}

/**
* Checks if the cookie containing the jwt is valid
* // Extracts the first valid jwt token found in the cookie or the Authorization header
*
* @param tokenProvider the artemis token provider used to generate and validate jwt's
* @param jwtCookie the cookie containing the jwt
* @return true if the jwt is valid, false if missing or invalid
* @param httpServletRequest the http request
* @param tokenProvider the artemis token provider used to generate and validate jwt's
* @return the valid jwt token or null if not found or invalid
*/
public static boolean isJwtCookieValid(TokenProvider tokenProvider, Cookie jwtCookie) {
public static @Nullable String extractValidJwt(HttpServletRequest httpServletRequest, TokenProvider tokenProvider) {
String jwtToken = getJwtFromCookie(WebUtils.getCookie(httpServletRequest, JWT_COOKIE_NAME));
if (isJwtValid(tokenProvider, jwtToken)) {
return jwtToken;
}
jwtToken = getJwtFromBearer(httpServletRequest.getHeader("Authorization"));
if (isJwtValid(tokenProvider, jwtToken)) {
return jwtToken;
}
return null;
}

/**
* Extracts the jwt token from the cookie
*
* @param jwtCookie the cookie with Key "jwt"
* @return the jwt token or null if not found
*/
private static @Nullable String getJwtFromCookie(Cookie jwtCookie) {
if (jwtCookie == null) {
return false;
return null;
}
String jwt = jwtCookie.getValue();
return StringUtils.hasText(jwt) && tokenProvider.validateTokenForAuthority(jwt);
return jwtCookie.getValue();
}

/**
* Extracts the jwt token from the Authorization header
*
* @param jwtBearer the content of the Authorization header
* @return the jwt token or null if not found
*/
private static @Nullable String getJwtFromBearer(String jwtBearer) {
if (!StringUtils.hasText(jwtBearer) || !jwtBearer.startsWith("Bearer ")) {
return null;
}

return jwtBearer.substring(7).trim();
}

/**
* Checks if the jwt token is valid
*
* @param tokenProvider the artemis token provider used to generate and validate jwt's
* @param jwtToken the jwt token
* @return true if the jwt is valid, false if missing or invalid
*/
private static boolean isJwtValid(TokenProvider tokenProvider, String jwtToken) {
return StringUtils.hasText(jwtToken) && tokenProvider.validateTokenForAuthority(jwtToken);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -95,11 +95,26 @@ public long getTokenValidity(boolean rememberMe) {
* @return JWT Token
*/
public String createToken(Authentication authentication, boolean rememberMe) {
return createToken(authentication, getTokenValidity(rememberMe));
}

/**
* Create JWT Token a fully populated <code>Authentication</code> object.
*
* @param authentication Authentication Object
* @param duration the Token lifetime
janthoXO marked this conversation as resolved.
Show resolved Hide resolved
* @param tools tools this token is used for
* @return JWT Token
*/
public String createToken(Authentication authentication, long duration, String... tools) {
String authorities = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.joining(","));

String toolClaims = String.join(",", tools);

long now = (new Date()).getTime();
janthoXO marked this conversation as resolved.
Show resolved Hide resolved
Date validity = new Date(now + getTokenValidity(rememberMe));
return Jwts.builder().subject(authentication.getName()).claim(AUTHORITIES_KEY, authorities).signWith(key, Jwts.SIG.HS512).expiration(validity).compact();
Date validity = new Date(now + duration);
return Jwts.builder().subject(authentication.getName()).claim(AUTHORITIES_KEY, authorities).claim("tools", toolClaims).signWith(key, Jwts.SIG.HS512).expiration(validity)
.compact();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

import static de.tum.cit.aet.artemis.core.config.Constants.PROFILE_CORE;

import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.Optional;

import jakarta.servlet.ServletException;
Expand Down Expand Up @@ -33,8 +36,11 @@
import de.tum.cit.aet.artemis.core.exception.AccessForbiddenException;
import de.tum.cit.aet.artemis.core.security.SecurityUtils;
import de.tum.cit.aet.artemis.core.security.UserNotActivatedException;
import de.tum.cit.aet.artemis.core.security.annotations.EnforceAtLeastStudent;
import de.tum.cit.aet.artemis.core.security.annotations.EnforceNothing;
import de.tum.cit.aet.artemis.core.security.jwt.JWTCookieService;
import de.tum.cit.aet.artemis.core.security.jwt.JWTFilter;
import de.tum.cit.aet.artemis.core.security.jwt.TokenProvider;
import de.tum.cit.aet.artemis.core.service.connectors.SAML2Service;

/**
Expand All @@ -49,12 +55,15 @@ public class PublicUserJwtResource {

private final JWTCookieService jwtCookieService;

private final TokenProvider tokenProvider;

private final AuthenticationManager authenticationManager;

private final Optional<SAML2Service> saml2Service;

public PublicUserJwtResource(JWTCookieService jwtCookieService, AuthenticationManager authenticationManager, Optional<SAML2Service> saml2Service) {
public PublicUserJwtResource(JWTCookieService jwtCookieService, TokenProvider tokenProvider, AuthenticationManager authenticationManager, Optional<SAML2Service> saml2Service) {
this.jwtCookieService = jwtCookieService;
this.tokenProvider = tokenProvider;
this.authenticationManager = authenticationManager;
this.saml2Service = saml2Service;
}
Expand All @@ -69,7 +78,7 @@ public PublicUserJwtResource(JWTCookieService jwtCookieService, AuthenticationMa
*/
@PostMapping("authenticate")
@EnforceNothing
public ResponseEntity<Void> authorize(@Valid @RequestBody LoginVM loginVM, @RequestHeader("User-Agent") String userAgent, HttpServletResponse response) {
public ResponseEntity<String> authorize(@Valid @RequestBody LoginVM loginVM, @RequestHeader("User-Agent") String userAgent, HttpServletResponse response) {

var username = loginVM.getUsername();
var password = loginVM.getPassword();
Expand All @@ -86,14 +95,41 @@ public ResponseEntity<Void> authorize(@Valid @RequestBody LoginVM loginVM, @Requ
ResponseCookie responseCookie = jwtCookieService.buildLoginCookie(rememberMe);
response.addHeader(HttpHeaders.SET_COOKIE, responseCookie.toString());

return ResponseEntity.ok().build();
return ResponseEntity.ok(responseCookie.getValue());
}
catch (BadCredentialsException ex) {
log.warn("Wrong credentials during login for user {}", loginVM.getUsername());
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
}

/**
* Sends a theia token back as cookie and bearer token
*
* @param request HTTP request
* @param response HTTP response
* @return the ResponseEntity with status 200 (ok), 401 (unauthorized)
*/
@PostMapping("theia-token")
@EnforceAtLeastStudent
public ResponseEntity<String> reKey(HttpServletRequest request, HttpServletResponse response) {
janthoXO marked this conversation as resolved.
Show resolved Hide resolved
// remaining time in milliseconds
var jwtToken = JWTFilter.extractValidJwt(request, tokenProvider);
if (jwtToken == null) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}

// get validity of the token
long tokenRemainingTime = tokenProvider.getExpirationDate(jwtToken).getTime() - new Date().getTime();

// 1 day validity
long maxDuration = Duration.ofDays(1).get(ChronoUnit.MILLIS);
ResponseCookie responseCookie = jwtCookieService.buildTheiaCookie(Math.min(tokenRemainingTime, maxDuration));

response.addHeader(HttpHeaders.SET_COOKIE, responseCookie.toString());
return ResponseEntity.ok(responseCookie.getValue());
}

/**
* Authorizes a User logged in with SAML2
*
Expand Down
Loading