Skip to content

Commit c019507

Browse files
committed
Add BearerTokenAuthentication
Fixes gh-7343
1 parent 346b8c2 commit c019507

File tree

2 files changed

+210
-0
lines changed

2 files changed

+210
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/*
2+
* Copyright 2002-2019 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package org.springframework.security.oauth2.server.resource.authentication;
17+
18+
import java.util.Collection;
19+
import java.util.Collections;
20+
import java.util.LinkedHashMap;
21+
import java.util.Map;
22+
23+
import org.springframework.security.core.GrantedAuthority;
24+
import org.springframework.security.core.SpringSecurityCoreVersion;
25+
import org.springframework.security.core.Transient;
26+
import org.springframework.security.oauth2.core.OAuth2AccessToken;
27+
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
28+
import org.springframework.util.Assert;
29+
30+
/**
31+
* An {@link org.springframework.security.core.Authentication} token that represents a successful authentication as
32+
* obtained through a bearer token.
33+
*
34+
* @author Josh Cummings
35+
* @since 5.2
36+
*/
37+
@Transient
38+
public class BearerTokenAuthentication extends AbstractOAuth2TokenAuthenticationToken<OAuth2AccessToken> {
39+
40+
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
41+
42+
private Map<String, Object> attributes;
43+
44+
/**
45+
* Constructs a {@link BearerTokenAuthentication} with the provided arguments
46+
*
47+
* @param principal The OAuth 2.0 attributes
48+
* @param credentials The verified token
49+
* @param authorities The authorities associated with the given token
50+
*/
51+
public BearerTokenAuthentication(OAuth2AuthenticatedPrincipal principal, OAuth2AccessToken credentials,
52+
Collection<? extends GrantedAuthority> authorities) {
53+
54+
super(credentials, principal, credentials, authorities);
55+
Assert.isTrue(credentials.getTokenType() == OAuth2AccessToken.TokenType.BEARER, "credentials must be a bearer token");
56+
this.attributes = Collections.unmodifiableMap(new LinkedHashMap<>(principal.getAttributes()));
57+
setAuthenticated(true);
58+
}
59+
60+
/**
61+
* {@inheritDoc}
62+
*/
63+
@Override
64+
public Map<String, Object> getTokenAttributes() {
65+
return this.attributes;
66+
}
67+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
/*
2+
* Copyright 2002-2019 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.security.oauth2.server.resource.authentication;
18+
19+
import java.net.URL;
20+
import java.time.Instant;
21+
import java.util.Collection;
22+
import java.util.Collections;
23+
import java.util.HashMap;
24+
import java.util.List;
25+
import java.util.Map;
26+
27+
import net.minidev.json.JSONObject;
28+
import org.junit.Before;
29+
import org.junit.Test;
30+
31+
import org.springframework.security.core.GrantedAuthority;
32+
import org.springframework.security.core.authority.AuthorityUtils;
33+
import org.springframework.security.oauth2.core.DefaultOAuth2AuthenticatedPrincipal;
34+
import org.springframework.security.oauth2.core.OAuth2AccessToken;
35+
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
36+
37+
import static org.assertj.core.api.Assertions.assertThat;
38+
import static org.assertj.core.api.Assertions.assertThatCode;
39+
import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.CLIENT_ID;
40+
import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.SUBJECT;
41+
import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.USERNAME;
42+
43+
/**
44+
* Tests for {@link BearerTokenAuthentication}
45+
*
46+
* @author Josh Cummings
47+
*/
48+
public class BearerTokenAuthenticationTests {
49+
private final OAuth2AccessToken token =
50+
new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
51+
"token", Instant.now(), Instant.now().plusSeconds(3600));
52+
private final String name = "sub";
53+
private Map<String, Object> attributesMap = new HashMap<>();
54+
private DefaultOAuth2AuthenticatedPrincipal principal;
55+
private final Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("USER");
56+
57+
@Before
58+
public void setUp() {
59+
this.attributesMap.put(SUBJECT, this.name);
60+
this.attributesMap.put(CLIENT_ID, "client_id");
61+
this.attributesMap.put(USERNAME, "username");
62+
this.principal = new DefaultOAuth2AuthenticatedPrincipal(this.attributesMap, null);
63+
}
64+
65+
@Test
66+
public void getNameWhenConfiguredInConstructorThenReturnsName() {
67+
OAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal(this.name, this.attributesMap, this.authorities);
68+
BearerTokenAuthentication authenticated = new BearerTokenAuthentication(principal, this.token, this.authorities);
69+
assertThat(authenticated.getName()).isEqualTo(this.name);
70+
}
71+
72+
@Test
73+
public void getNameWhenHasNoSubjectThenReturnsNull() {
74+
OAuth2AuthenticatedPrincipal principal =
75+
new DefaultOAuth2AuthenticatedPrincipal(Collections.singletonMap("claim", "value"), null);
76+
BearerTokenAuthentication authenticated = new BearerTokenAuthentication(principal, this.token, null);
77+
assertThat(authenticated.getName()).isNull();
78+
}
79+
80+
@Test
81+
public void getNameWhenTokenHasUsernameThenReturnsUsernameAttribute() {
82+
BearerTokenAuthentication authenticated = new BearerTokenAuthentication(this.principal, this.token, null);
83+
assertThat(authenticated.getName()).isEqualTo(this.principal.getAttribute(SUBJECT));
84+
}
85+
86+
@Test
87+
public void constructorWhenTokenIsNullThenThrowsException() {
88+
assertThatCode(() -> new BearerTokenAuthentication(this.principal, null, null))
89+
.isInstanceOf(IllegalArgumentException.class)
90+
.hasMessageContaining("token cannot be null");
91+
}
92+
93+
@Test
94+
public void constructorWhenCredentialIsNullThenThrowsException() {
95+
assertThatCode(() -> new BearerTokenAuthentication(null, this.token, null))
96+
.isInstanceOf(IllegalArgumentException.class)
97+
.hasMessageContaining("principal cannot be null");
98+
}
99+
100+
@Test
101+
public void constructorWhenPassingAllAttributesThenTokenIsAuthenticated() {
102+
OAuth2AuthenticatedPrincipal principal =
103+
new DefaultOAuth2AuthenticatedPrincipal("harris", Collections.singletonMap("claim", "value"), null);
104+
BearerTokenAuthentication authenticated = new BearerTokenAuthentication(principal, this.token, null);
105+
assertThat(authenticated.isAuthenticated()).isTrue();
106+
}
107+
108+
@Test
109+
public void getTokenAttributesWhenHasTokenThenReturnsThem() {
110+
BearerTokenAuthentication authenticated =
111+
new BearerTokenAuthentication(this.principal, this.token, Collections.emptyList());
112+
assertThat(authenticated.getTokenAttributes()).isEqualTo(this.principal.getAttributes());
113+
}
114+
115+
@Test
116+
public void getAuthoritiesWhenHasAuthoritiesThenReturnsThem() {
117+
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("USER");
118+
BearerTokenAuthentication authenticated =
119+
new BearerTokenAuthentication(this.principal, this.token, authorities);
120+
assertThat(authenticated.getAuthorities()).isEqualTo(authorities);
121+
}
122+
123+
// gh-6843
124+
@Test
125+
public void constructorWhenDefaultParametersThenSetsPrincipalToAttributesCopy() {
126+
JSONObject attributes = new JSONObject();
127+
attributes.put("active", true);
128+
OAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal(attributes, null);
129+
BearerTokenAuthentication token = new BearerTokenAuthentication(principal, this.token, null);
130+
assertThat(token.getPrincipal()).isNotSameAs(attributes);
131+
assertThat(token.getTokenAttributes()).isNotSameAs(attributes);
132+
}
133+
134+
// gh-6843
135+
@Test
136+
public void toStringWhenAttributesContainsURLThenDoesNotFail() throws Exception {
137+
JSONObject attributes = new JSONObject(Collections.singletonMap("iss", new URL("https://idp.example.com")));
138+
OAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal(attributes, null);
139+
BearerTokenAuthentication token = new BearerTokenAuthentication(principal, this.token, null);
140+
assertThatCode(token::toString)
141+
.doesNotThrowAnyException();
142+
}
143+
}

0 commit comments

Comments
 (0)