NextJs middleware can't verify JWT from java spring backend - spring

Im using Nextjs mainly for my frontend and Java springboot for my backend. However I want to use the nextjs middleware for protecting my routes via JWT. Since jsonwebtoken can't run on edge functions I am using jose.
After attempting to grab the JWT from cookies, I try to verify it and get this message:
JWSSignatureVerificationFailed: signature verification failed
Here is the signing of my token in the spring backend:
public static String generateJwtToken(AppUser user) {
Map<String, Object> claims = new HashMap<>();
return Jwts.builder()
.setClaims(claims)
.setSubject(user.getUsername())
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + TOKEN_VALIDITY * 1000))
.signWith(SignatureAlgorithm.HS512, jwtSecret)
.compact();
}
and here is the attempt to verify it in my nextjs middleware file:
const token = request.cookies.get('jwt');
const { payload } = await jwtVerify(
token,
new TextEncoder().encode(process.env.SECRET_KEY)
);
Note: the jwtSecret and SECRET_KEY are the exact same values coming from the exact same .env file. Any help would be greatly appreciated

Found my answer more or less here https://github.com/auth0/node-jsonwebtoken/issues/208#issuecomment-231861138. This exact comment explains what should be happening with the secret key.
As for what I fixed in the code, I had to return the secret key as a bytes array.
.signWith(SignatureAlgorithm.HS512, jwtSecret.getBytes("UTF-8"))

Related

Differentiate requests originating from different clients in OAuth2 framework of springboot

I have 3 different clients say mobile, web, iot. I am using grant_type = password and obtaining accessToken. I get requests GET /access/resource from all the clients. I want to process them differently based on their client ID. I know /oauth/check_token reponds with client_id but how to extract it in resource server
Use JWT, when authorization server creates token, default AccessTokenConverter implementation DefaultAccessTokenConverter's convertAccessToken method does: "response.put(this.clientIdAttribute, clientToken.getClientId());" for the token to also include client id. Above mentioned response is just a hashmap which will be converted to JWT.
When your resource server gets hit on GET /access/resource:
#RequestMapping("/access/resource")
public #ResponseBody Map<String,Object> getRes() throws IOException {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
ObjectMapper objMapper = new ObjectMapper();
Map<String,Object> map = objMapper.convertValue(auth.getDetails(),Map.class);
Jwt jwt = JwtHelper.decode((String) map.get("tokenValue"));
Map<String,Object> claims = objMapper.readValue(jwt.getClaims(),Map.class);
// This is what you want
String clnt_id = (String) claims.get("client_id"); <<------- here
// your logic here based on clnt_id
// ex: if(clnt_id.equals("Specific client"){}
...
return Collections.emptyMap();;
}
OR
OAuth2Request also includes resolved client id:
Authentication auth =
SecurityContextHolder.getContext().getAuthentication();
String cliend_id = ((OAuth2Authentication) auth).getOAuth2Request().getClientId()
This option can be applied even if JWT is not used as Oauth2request is always there.
Take a look here to understand better:

Are there any endpoint for check token in ADFS?

I am using Spring Oauth2 and ADFS for security purpose. However I can not find the endpoint for checking token from response of ADFS.
I also have Spring Authorization Provider which is written in Java. And my application called it by using these properties:
security.oauth2.client.clientId=myclient
security.oauth2.client.client-secret= mysecret
security.oauth2.client.userAuthorizationUri= http://127.0.0.1:9999/oauth/authorize?resource=https://localhost:8443/login
security.oauth2.client.accessTokenUri= http://127.0.0.1:9999/oauth/token
security.oauth2.resource.user-info-uri= http://127.0.0.1:9999/login
security.oauth2.resource.token-info-uri= http://127.0.0.1:9999/oauth/check_token
security.oauth2.client.tokenName=code
security.oauth2.client.authenticationScheme=query
security.oauth2.client.clientAuthenticationScheme=form
security.oauth2.client.grant-type=authorization_code
And I have changed the values of the properties to connect with ADFS
security.oauth2.client.clientId=myclient
security.oauth2.client.client-secret= myclient
security.oauth2.client.userAuthorizationUri= https://adfs.local/adfs/oauth2/authorize?resource=https://localhost:8443/login
security.oauth2.client.accessTokenUri= https://adfs.local/adfs/oauth2/token
security.oauth2.resource.user-info-uri= https://adfs.local/adfs/oauth2/userinfo
security.oauth2.resource.token-info-uri= https://adfs.local/adfs/oauth2/check_token
security.oauth2.client.tokenName=code
security.oauth2.client.authenticationScheme=query
security.oauth2.client.clientAuthenticationScheme=form
security.oauth2.client.grant-type=authorization_code
However, I found that https://adfs.local/adfs/oauth2/check_token is invalid in ADFS.
How can I get the check_token in ADFS? check_token is Token Introspection Endpoint, however, this endpoint doesn't return node 'active' according to OAuth 2 Extension which is mandatory. See this link
This is what Spring Authorization Provider do when return check_token endpoint
#RequestMapping(value = "/oauth/check_token", method = RequestMethod.POST)
#ResponseBody
public Map<String, ?> checkToken(#RequestParam("token") String value) {
OAuth2AccessToken token = resourceServerTokenServices.readAccessToken(value);
if (token == null) {
throw new InvalidTokenException("Token was not recognised");
}
if (token.isExpired()) {
throw new InvalidTokenException("Token has expired");
}
OAuth2Authentication authentication = resourceServerTokenServices.loadAuthentication(token.getValue());
Map<String, Object> response = (Map<String, Object>)accessTokenConverter.convertAccessToken(token, authentication);
// gh-1070
response.put("active", true); // Always true if token exists and not expired
return response;
}
ADFS has no such endpoint and I don't believe it's part of the spec?
You could use:
https://[Your ADFS hostname]/adfs/.well-known/openid-configuration
to get the keys to check the JWT yourself which is the usual practice.
There are many resources on how to check the JWT e.g. this.

Generate JWT OAuth2 Access token without password

My Spring Boot authorization service is able to create JWT tokens for users with correct credentials. It shall also be possible to get a token via social login (Facebook in this case).
The Facebook authentication already works and I find myself redirected to the following endpoint after I get the users's Facebook data.
I could create the JWT token completely from scratch, but that is not what I want. I want to use the already configured (with key pair and so on) TokenServices from my authentication server.
The only way I found was via TokenEndpoint. The problem is that I need the user's password, which I don't have and shouldn't have at this point.
How can I generate the token from what I already configured?
This endpoint is where I end up after Facebook's redirect:
#GetMapping("/loginSuccess")
fun getLoginInfo(authentication: OAuth2AuthenticationToken): ResponseEntity<OAuth2AccessToken> {
val client = authorizedClientService.loadAuthorizedClient<OAuth2AuthorizedClient>(authentication.authorizedClientRegistrationId, authentication.name)
val userInfoEndpointUri = client.clientRegistration.providerDetails.userInfoEndpoint.uri
if (!StringUtils.isEmpty(userInfoEndpointUri)) {
val restTemplate = RestTemplate()
val headers = HttpHeaders()
headers.add(HttpHeaders.AUTHORIZATION, "Bearer " + client.accessToken.tokenValue)
val entity = HttpEntity("", headers)
val response = restTemplate.exchange(userInfoEndpointUri, HttpMethod.GET, entity, Map::class.java)
// At this point I have the email address of the user and I am able to
// map it to my own User Entity
// This is where I would like to create a token and return it
// However, the following generation process requires the user's password
return authService.generateToken((response.body as Map<*, *>)["email"] as String)
}
throw AuthenticationException("Error")
}
I would like to use getAccessToken(OAuth2Authentication authentication) in JwtTokenStore but its implementation returns null:
#Override
public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
// We don't want to accidentally issue a token, and we have no way to
// reconstruct the refresh token
return null;
}

Spring Framework - Where to parse JWT for custom claim?

I have created a Spring JWT authorization application. JWT contains some custom claims. On a resource server side, I wonder, where should I parse the JWT token to collect and check these claims? Should I do this in a controller or in some filter? Whats the best practice? Maybe you have some example?
You can use a combination of a Jackson Object Mapper and Spring Security classes, namely Jwt, JwtHelper and Authentication. You can get the authentication by using Spring Security's static context object and then parse the token you receive using the JwtHelper.
ObjectMapper objectMapper = new ObjectMapper();
Authentication authentication =
SecurityContextHolder.getContext().getAuthentication();
Map<String, Object> map =
objectMapper.convertValue(authentication.getDetails(), Map.class);
// create a token object to represent the token that is in use.
Jwt jwt = JwtHelper.decode((String) map.get("tokenValue"));
// jwt.getClaims() will return a JSON object of all the claims in your token
// Convert claims JSON object into a Map so we can get the value of a field
Map<String, Object> claims = objectMapper.readValue(jwt.getClaims(), Map.class);
String customField = (String) claims.get("you_custom_field_name");
I would suggest debugging and putting a breakpoint on the third line in the code above. At that point, expose the authentication object. I might have some useful details you'll need later.
This can all be done on the controller. I'm not sure how to use the filter to do so.
you can also use springframework.boot.json.JsonParser:
JsonParser parser = JsonParserFactory.getJsonParser();
Map<String, ?> tokenData = parser.parseMap(JwtHelper.decode(token).getClaims());
> tokenData.get("VALID_KEY");
I'm using this:
private Claim getClaim(String claimKey) {
Authentication token = SecurityContextHolder.getContext().getAuthentication();
try {
DecodedJWT jwt = JWT.decode(token.getCredentials().toString());
return jwt.getClaim(claimKey);
} catch (JWTVerificationException ex) {
throw new RuntimeException(ex);
}
}

Setting OAuth2 token for RestTemplate in an app that uses both #ResourceServer and #EnableOauth2Sso

On my current project I have an app that has a small graphical piece that users authenticate using SSO, and a portion that is purely API where users authenticate using an Authorization header.
For example:
/ping-other-service is accessed using SSO.
/api/ping-other-service is accessed using a bearer token
Being all cloud native our app communicates with other services that uses the same SSO provider using JWT tokens (UAA), so I figured we'd use OAuth2RestTemplate since according to the documentation it can magically insert the authentication credentials. It does do that for all endpoints that are authenticated using SSO. But when we use an endpoint that is authed through bearer token it doesn't populate the rest template.
My understanding from the documentation is that #EnableOAuth2Client will only extract the token from a SSO login, not auth header?
What I'm seeing
Failed request and what it does:
curl -H "Authorization: Bearer <token>" http://localhost/api/ping-other-service
Internally uses restTemplate to call http://some-other-service/ping which responds 401
Successful request and what it does:
Chrome http://localhost/ping-other-service
Internally uses restTemplate to call http://some-other-service/ping which responds 200
How we worked around it
To work around this I ended up creating the following monstrosity which will extract the token from the OAuth2ClientContext if it isn't available from an authorization header.
#PostMapping(path = "/ping-other-service")
public ResponseEntity ping(#PathVariable String caseId, HttpServletRequest request, RestTemplate restTemplate) {
try {
restTemplate.postForEntity(adapterUrl + "/webhook/ping", getRequest(request), Map.class);
} catch (HttpClientErrorException e) {
e.printStackTrace();
return new ResponseEntity(HttpStatus.SERVICE_UNAVAILABLE);
}
return new ResponseEntity(HttpStatus.OK);
}
private HttpEntity<?> getRequest(HttpServletRequest request) {
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + getRequestToken(request));
return new HttpEntity<>(null, headers);
}
private String getRequestToken(HttpServletRequest request) {
Authentication token = new BearerTokenExtractor().extract(request);
if (token != null) {
return (String) token.getPrincipal();
} else {
OAuth2AccessToken accessToken = oAuth2ClientContext.getAccessToken();
if (accessToken != null) {
return accessToken.getValue();
}
}
throw new ResourceNotFound("No valid access token found");
}
In the /api/** resources there is an incoming token, but because you are using JWT the resource server can authenticate without calling out to the auth server, so there is no OAuth2RestTemplate just sitting around waiting for you to re-use the context in the token relay (if you were using UserInfoTokenServices there would be one). You can create one though quite easily, and pull the incoming token out of the SecurityContext. Example:
#Autowired
private OAuth2ProtectedResourceDetails resource;
private OAuth2RestTemplate tokenRelayTemplate(Principal principal) {
OAuth2Authentication authentication = (OAuth2Authentication) principal;
OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
details.getTokenValue();
OAuth2ClientContext context = new DefaultOAuth2ClientContext(new DefaultOAuth2AccessToken(details.getTokenValue()));
return new OAuth2RestTemplate(resource, context);
}
You could probably turn that method into #Bean (in #Scope("request")) and inject the template with a #Qualifier if you wanted.
There's some autoconfiguration and a utility class to help with this pattern in Spring Cloud Security, e.g: https://github.com/spring-cloud/spring-cloud-security/blob/master/spring-cloud-security/src/main/java/org/springframework/cloud/security/oauth2/client/AccessTokenContextRelay.java
I came across this problem when developing a Spring resource server, and I needed to pass the OAuth2 token from a request to the restTemplate for a call to a downstream resource server. Both resource servers use the same auth server, and I found Dave's link helpful but I had to dig a bit to find out how to implement this. I ended up finding the documentation here, and it turn's out the implemetation was very simple. I was using #EnableOAuth2Client, so I had to create the restTemplate bean with the injected OAuth2ClientContext and create the appropriate resource details. In my case it was ClientCredentialsResourceDetails. Thanks for all great work Dave!
#Bean
public OAuth2RestOperations restTemplate (OAuth2ClientContext context) {
ClientCredentialsResourceDetails details = new ClientCredentialsResourceDetails();
// Configure the details here
return new OAuth2RestTemplate(details, context)
}
#Dave Syer
My UAA service is also an oauth2 client, which needs to relay JWT tokens coming in from Zuul. When configuring the oauth2 client the following way
#Configuration
#EnableOAuth2Client
#RibbonClient(name = "downstream")
public class OAuthClientConfiguration {
#Bean
public OAuth2RestTemplate restTemplate(OAuth2ProtectedResourceDetails resource, OAuth2ClientContext context) {
return new OAuth2RestTemplate(resource, context);
}
}
I do get a 401 response from the downstream service as my access token has a very short validity and the AccessTokenContextRelay does not update an incoming access token (Zuul does renew expired access tokens by the refresh token).
The OAuth2RestTemplate#getAccessToken will never acquire a new access token as the isExpired on the access token stored by the AccessTokenContextRelay drops the validity and refresh token information.
How can this by solved?

Resources