Your web application may run on the server-side using Spring Boot framework. For now, you need to integrate Auth in Spring Boot manually. This article guides you on how to finish it step by step. And we use Gradle, Java, and Spring Security to take the example.
Since Spring Boot and Spring Security have built-in support for both OAuth2 resource server and JWT validation, you DO NOT need to add additional libraries from Auth to integrate.
All the latest Auth Authorization Server Configurations can be found by https:///.well-known/openid-configuration, including the issuer, jwks_uri and other authorization configs. For example:
audience: The unique API identifier (i.e. API indicator) of your protected API resource.
spring.security.oauth2.resourceserver.jwt.issuer-uri: The iss claim value and the issuer URI in the JWT issued by Auth. Fill out the issuer value from the previous section.
spring.security.oauth2.resourceserver.jwt.jwk-set-uri: Spring Security uses this URI to get the authorization server's public keys to validate JWT signatures. Fill out the jwks_uri value from the previous section.
Provide your own AudienceValidator class that implements the OAuth2TokenValidator interface to validate whether the required audience is present in the JWT.
// path/to/project/src/main/java/io/auth/springboot/sample/validator/AudienceValidator.java
package io.auth.springboot.sample.validator;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
import org.springframework.security.oauth2.jwt.Jwt;
public class AudienceValidator implements OAuth2TokenValidator<Jwt> {
private final OAuth2Error oAuth2Error = new OAuth2Error("invalid_token", "Required audience not found", null);
private final String audience;
public AudienceValidator(String audience) {
this.audience = audience;
}
@Override
public OAuth2TokenValidatorResult validate(Jwt jwt) {
if (!jwt.getAudience().contains(audience)) {
return OAuth2TokenValidatorResult.failure(oAuth2Error);
}
return OAuth2TokenValidatorResult.success();
}
}
If succeeded, you will get a response with 200 status:
HTTP/1.1 200
...
Otherwise, you will get a response with 401 status like this:
HTTP/1.1 401
...
WWW-Authenticate: Bearer error="invalid_token", error_description="An error occurred while attempting to decode the Jwt: Signed JWT rejected: Invalid signature", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1"