Skip to content

Introduce JwtEncoder #87

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

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
@@ -0,0 +1,48 @@
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.server.authorization.jose;

import org.springframework.util.Assert;

import java.security.Key;
import java.util.Collections;
import java.util.List;

/**
* Internal implementation of {@link KeyManager} that manages a single {@link Key}.
*
* @author Anoop Garlapati
* @since 0.0.1
*/
final class DefaultKeyManager implements KeyManager {

private Key key;

DefaultKeyManager(Key key) {
Assert.notNull(key, "key cannot be null");
this.key = key;
}

@Override
public List<Key> getKeys() {
return Collections.singletonList(this.key);
}

@Override
public Key getActiveKey() {
return this.key;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.server.authorization.jose;

/**
* The Registered Header Parameter Names defined by the JSON Web Signature (JWS) specification
* that may be contained in the JSON object JOSE Header.
*
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7515#section-4.1">JWS Headers</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7797#section-3">B64 Header Parameter</a>
*/
public interface JoseHeaderNames {

String ALG = "alg";

String JKU = "jku";

String JWK = "jwk";

String KID = "kid";

String X5U = "x5u";

String X5C = "x5c";

String X5T = "x5t";

String X5T256 = "x5t#256";

String TYP = "typ";

String CTY = "cty";

String CRIT = "crit";

String B64 = "b64";
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.server.authorization.jose;

import org.springframework.core.convert.TypeDescriptor;
import org.springframework.security.oauth2.core.converter.ClaimConversionService;
import org.springframework.security.oauth2.jose.jws.MacAlgorithm;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.util.Assert;

import java.net.URI;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

/**
* A representation of &quot;headers&quot; that may be contained
* in the JSON object JOSE Header of a JSON Web Signature (JWS).
*
* @author Anoop Garlapati
* @since 0.0.1
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7515#section-4">JOSE Header of JWS</a>
*/
public class JoseHeaders {

private final Map<String, Object> headers;

protected JoseHeaders(Map<String, Object> headers) {
Assert.notEmpty(headers, "headers cannot be empty");
this.headers = Collections.unmodifiableMap(new LinkedHashMap<>(headers));
}

public SignatureAlgorithm getSignatureAlgorithm() {
return SignatureAlgorithm.from(getHeaderAsString("alg"));
}

public MacAlgorithm getMacAlgorithm() {
return MacAlgorithm.from(getHeaderAsString("alg"));
}

public String getType() {
return getHeaderAsString("typ");
}

public Map<String, Object> getHeaders() {
return this.headers;
}

public String getHeaderAsString(String header) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I realize that these are following the JwtClaimAccessor pattern; however, I think that it's better to coerce the values to the correct type on write instead of converting them on each read.

Further, I think the JwtClaimAccessor makes a bit more sense when we are reading a JWT that another library has deserialized and chosen the types for each claim. Since we are the ones serializing in this case, I'm not seeing a huge need for these converters.

Is there any reason that we can't just have one method for now:

public <H> H getHeader(String name) {
    return (H) this.headers.get(name)
}

and add the others later on, if needed?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree that since we are the ones serializing we might not need converters. I will simplify this in my next draft.

return !containsHeader(header) ? null :
ClaimConversionService.getSharedInstance().convert(getHeaders().get(header), String.class);
}

@SuppressWarnings("unchecked")
public List<String> getHeaderAsStringList(String header) {
if (!containsHeader(header)) {
return null;
}
final TypeDescriptor sourceDescriptor = TypeDescriptor.valueOf(Object.class);
final TypeDescriptor targetDescriptor = TypeDescriptor.collection(
List.class, TypeDescriptor.valueOf(String.class));
Object headerValue = getHeaders().get(header);
List<String> convertedValue = (List<String>) ClaimConversionService.getSharedInstance().convert(
headerValue, sourceDescriptor, targetDescriptor);
if (convertedValue == null) {
throw new IllegalArgumentException("Unable to convert header '" + header +
"' of type '" + headerValue.getClass() + "' to List.");
}
return convertedValue;
}

public URI getHeaderAsURI(String header) {
if (!containsHeader(header)) {
return null;
}
Object headerValue = getHeaders().get(header);
URI convertedValue = ClaimConversionService.getSharedInstance().convert(headerValue, URI.class);
if (convertedValue == null) {
throw new IllegalArgumentException("Unable to convert header '" + header +
"' of type '" + headerValue.getClass() + "' to URI.");
}
return convertedValue;
}

public Boolean getHeaderAsBoolean(String header) {
return !containsHeader(header) ? null :
ClaimConversionService.getSharedInstance().convert(getHeaders().get(header), Boolean.class);
}

private Boolean containsHeader(String header) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this ever be null? Does it have to be a Boolean?

Assert.notNull(header, "header cannot be null");
return getHeaders().containsKey(header);
}

public static class Builder {
private Map<String, Object> headers = new LinkedHashMap<>();

public Builder() {
}

public Builder(JoseHeaders joseHeaders) {
Assert.notNull(joseHeaders, "joseHeaders cannot be null");
this.headers = joseHeaders.headers;
}

public Builder header(String name, Object value) {
Assert.notNull(name, "name cannot be null");
this.headers.put(name, value);
return this;
}

public Builder headers(Consumer<Map<String, Object>> headersConsumer) {
Assert.notNull(headersConsumer, "headersConsumer cannot be null");
headersConsumer.accept(this.headers);
return this;
}

public Builder signatureAlgorithm(SignatureAlgorithm signatureAlgorithm) {
Assert.notNull(signatureAlgorithm, "signatureAlgorithm cannot be null");
this.header("alg", signatureAlgorithm.getName());
return this;
}

public Builder macAlgorithm(MacAlgorithm macAlgorithm) {
Assert.notNull(macAlgorithm, "macAlgorithm cannot be null");
this.header("alg", macAlgorithm.getName());
return this;
}

public Builder type(String type) {
Assert.notNull(type, "type cannot be null");
this.header("typ", type);
return this;
}

public JoseHeaders build() {
return new JoseHeaders(this.headers);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.server.authorization.jose;

import org.springframework.security.oauth2.jwt.JwtClaimAccessor;
import org.springframework.util.Assert;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Consumer;

/**
* A representation of &quot;claims&quot; that may be contained
* in the JSON object JWT Claims Set of a JSON Web Token (JWT).
*
* @author Anoop Garlapati
* @since 0.0.1
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7519#section-4">JWT Claims</a>
*/
public class JwtClaimsSet implements JwtClaimAccessor {

private final Map<String, Object> claims;

protected JwtClaimsSet(Map<String, Object> claims) {
Assert.notEmpty(claims, "claims cannot be null");
this.claims = Collections.unmodifiableMap(new LinkedHashMap<>(claims));
}

@Override
public Map<String, Object> getClaims() {
return this.claims;
}

public static class Builder {
private Map<String, Object> claims = new LinkedHashMap<>();

public Builder() {
}

public Builder(JwtClaimsSet jwtClaimsSet) {
Assert.notNull(jwtClaimsSet, "jwtClaimsSet cannot be null");
this.claims = jwtClaimsSet.claims;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

claims is an unmodifiable map, you should add all its entries to this.claims instead.

}

public Builder claim(String name, Object value) {
Assert.notNull(name, "name cannot be null");
this.claims.put(name, value);
return this;
}

public Builder claims(Consumer<Map<String, Object>> claimsConsumer) {
Assert.notNull(claimsConsumer, "claimsConsumer cannot be null");
claimsConsumer.accept(this.claims);
return this;
}

public JwtClaimsSet build() {
return new JwtClaimsSet(this.claims);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.server.authorization.jose;

import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtException;

/**
* Implementations of this interface are responsible for &quot;encoding&quot;
* a JSON Web Token (JWT) from it's unsecured representation {@link UnsecuredJwt}
* to secured representation {@link Jwt}.
*
* @author Anoop Garlapati
* @since 0.0.1
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7519">JSON Web Token (JWT)</a>
*/
@FunctionalInterface
public interface JwtEncoder {

/**
* Encodes the JWT from its unsecured format {@link UnsecuredJwt} and returns a {@link Jwt}.
*
* @param unsecuredJwt the unsecured JWT representation
* @return a {@link Jwt}
* @throws JwtException if an exception occurs while attempting to encode the JWT
*/
Jwt encode(UnsecuredJwt unsecuredJwt) throws JwtException;
}
Loading