Przykład do tego o czym mówie.
Robimy security config, żeby nie bawić się w jakieś branie stringowego tokena i validowanie go ręcznie:
@Configuration
public class TokenSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/costam/costam")
.authorizeRequests()
.antMatchers("/costam/costam").authenticated()
.and()
.oauth2ResourceServer()
.jwt();
}
}
W propertisach mamy spring.security.oauth2.resourceserver.jwt.jwk-set-uri=URL_DO_KLUCZA_PUBLICZNEGO_SERVERA_OD_TOKENÓW
Następnie robimy sobie kontroler:
@RestController
@RequestMapping("/costam")
public class TokenAuthController {
@GetMapping(value="costam")
public A method(Authentication principal){
// costam
}
}
I voila. Teraz chcemy to testować, to bierzemy sobie coś w stylu:
httpMock = HttpNoDepsMockProvider
.newConfig()
.build("httpMock");
httpMock .start(new DummyRunnerContext());
Przypisujemy do tego naszego property spring.security.oauth2.resourceserver.jwt.jwk-set-uri
w teście adres tego postawionego http servera (localhost:jakiś_port) a w tekście robimy sobie jakieś:
RSAKey rsaJWK = new RSAKeyGenerator(2048)
.keyID("someId")
.keyUse(KeyUse.SIGNATURE)
.generate();
JWSSigner signer = new RSASSASigner(rsaJWK);
JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
.subject(user.getName())
.jwtID(UUID.randomUUID().toString())
.audience("someAudience")
.issuer("someIssuer")
.expirationTime(new Date(new Date().getTime() + 60 * 1000))
.build();
SignedJWT signedJWT = new SignedJWT(
new JWSHeader.Builder(JWSAlgorithm.RS256).keyID(rsaJWK.getKeyID()).build(),
claimsSet);
signedJWT.sign(signer);
RSAKey rsaPublicJWK = rsaJWK.toPublicJWK();
String pubkey = rsaPublicJWK.toJSONObject().toString();
httpMock.createRule()
.whenCalledWith(Method.GET, "/")
.thenRespondWith(MockRuleProvider.Body.asJsonFrom("{\"keys\":[" + pubkey + "]}"));
return signedJWT.serialize();
I voila, mamy wygenerowany token który poprawnie zwaliduje się, jak Spring security uderzy po klucz publiczny do naszego http servera.
A jak testujemy naszą aplikację? Tworzymy http clienta i stukamy sobie w localhost:server.port