如何为ADFS配置Spring Boot安全性OAuth2?
是否有人成功将ADFS作为身份提供者配置了Spring Boot" title="Spring Boot">Spring Boot
OAuth2?我在Facebook上成功遵循了本教程,网址为https://spring.io/guides/tutorials/spring-boot-
oauth2/,但ADFS似乎没有userInfoUri。我认为ADFS会以令牌本身(JWT格式?)返回声明数据,但不确定如何使它与Spring一起使用。到目前为止,这是我的属性文件中包含的内容:
security: oauth2:
client:
clientId: [client id setup with ADFS]
userAuthorizationUri: https://[adfs domain]/adfs/oauth2/authorize?resource=[MyRelyingPartyTrust]
accessTokenUri: https://[adfs domain]/adfs/oauth2/token
tokenName: code
authenticationScheme: query
clientAuthenticationScheme: form
grant-type: authorization_code
resource:
userInfoUri: [not sure what to put here?]
回答:
ADFS将用户信息嵌入到oauth令牌中。您需要创建并覆盖org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoTokenServices对象以提取此信息并将其添加到Principal对象
:https : //spring.io/guides/tutorials/spring-boot-
oauth2/。使用以下应用程序属性(填写您自己的域):
security: oauth2:
client:
clientId: [client id setup with ADFS]
userAuthorizationUri: https://[adfs domain]/adfs/oauth2/authorize?resource=[MyRelyingPartyTrust]
accessTokenUri: https://[adfs domain]/adfs/oauth2/token
tokenName: code
authenticationScheme: query
clientAuthenticationScheme: form
grant-type: authorization_code
resource:
userInfoUri: https://[adfs domain]/adfs/oauth2/token
注意:我们将忽略userInfoUri中的任何内容,但是Spring OAuth2似乎需要一些内容。
AdfsUserInfoTokenServices,您可以在下面复制和调整
(您将需要对其进行清理)。这是Spring类的副本;您可以根据需要扩展它,但是我进行了很多更改,这些更改似乎并没有给我带来什么好处:
package edu.bowdoin.oath2sample;import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.security.oauth2.resource.AuthoritiesExtractor;
import org.springframework.boot.autoconfigure.security.oauth2.resource.FixedAuthoritiesExtractor;
import org.springframework.boot.autoconfigure.security.oauth2.resource.FixedPrincipalExtractor;
import org.springframework.boot.autoconfigure.security.oauth2.resource.PrincipalExtractor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.client.OAuth2RestOperations;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.util.Assert;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
public class AdfsUserInfoTokenServices implements ResourceServerTokenServices {
protected final Logger logger = LoggerFactory.getLogger(getClass());
private final String userInfoEndpointUrl;
private final String clientId;
private String tokenType = DefaultOAuth2AccessToken.BEARER_TYPE;
private AuthoritiesExtractor authoritiesExtractor = new FixedAuthoritiesExtractor();
private PrincipalExtractor principalExtractor = new FixedPrincipalExtractor();
public AdfsUserInfoTokenServices(String userInfoEndpointUrl, String clientId) {
this.userInfoEndpointUrl = userInfoEndpointUrl;
this.clientId = clientId;
}
public void setTokenType(String tokenType) {
this.tokenType = tokenType;
}
public void setRestTemplate(OAuth2RestOperations restTemplate) {
// not used
}
public void setAuthoritiesExtractor(AuthoritiesExtractor authoritiesExtractor) {
Assert.notNull(authoritiesExtractor, "AuthoritiesExtractor must not be null");
this.authoritiesExtractor = authoritiesExtractor;
}
public void setPrincipalExtractor(PrincipalExtractor principalExtractor) {
Assert.notNull(principalExtractor, "PrincipalExtractor must not be null");
this.principalExtractor = principalExtractor;
}
@Override
public OAuth2Authentication loadAuthentication(String accessToken)
throws AuthenticationException, InvalidTokenException {
Map<String, Object> map = getMap(this.userInfoEndpointUrl, accessToken);
if (map.containsKey("error")) {
if (this.logger.isDebugEnabled()) {
this.logger.debug("userinfo returned error: " + map.get("error"));
}
throw new InvalidTokenException(accessToken);
}
return extractAuthentication(map);
}
private OAuth2Authentication extractAuthentication(Map<String, Object> map) {
Object principal = getPrincipal(map);
List<GrantedAuthority> authorities = this.authoritiesExtractor
.extractAuthorities(map);
OAuth2Request request = new OAuth2Request(null, this.clientId, null, true, null,
null, null, null, null);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
principal, "N/A", authorities);
token.setDetails(map);
return new OAuth2Authentication(request, token);
}
/**
* Return the principal that should be used for the token. The default implementation
* delegates to the {@link PrincipalExtractor}.
* @param map the source map
* @return the principal or {@literal "unknown"}
*/
protected Object getPrincipal(Map<String, Object> map) {
Object principal = this.principalExtractor.extractPrincipal(map);
return (principal == null ? "unknown" : principal);
}
@Override
public OAuth2AccessToken readAccessToken(String accessToken) {
throw new UnsupportedOperationException("Not supported: read access token");
}
private Map<String, Object> getMap(String path, String accessToken) {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Getting user info from: " + path);
}
try {
DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(
accessToken);
token.setTokenType(this.tokenType);
logger.debug("Token value: " + token.getValue());
String jwtBase64 = token.getValue().split("\\.")[1];
logger.debug("Token: Encoded JWT: " + jwtBase64);
logger.debug("Decode: " + Base64.getDecoder().decode(jwtBase64.getBytes()));
String jwtJson = new String(Base64.getDecoder().decode(jwtBase64.getBytes()));
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(jwtJson, new TypeReference<Map<String, Object>>(){});
}
catch (Exception ex) {
this.logger.warn("Could not fetch user details: " + ex.getClass() + ", "
+ ex.getMessage());
return Collections.<String, Object>singletonMap("error",
"Could not fetch user details");
}
}
}
使用getMap方法可以解析令牌值,并提取和解码JWT格式的用户信息(可以在此处改进错误检查,这是一个粗略的草稿,但可以提供要点)。请参阅此链接的底部以获取有关ADFS如何将数据嵌入令牌中的信息:https :
//blogs.technet.microsoft.com/askpfeplat/2014/11/02/adfs-deep-dive-comparing-
ws-fed- saml-and-oauth
/
@Autowiredprivate ResourceServerProperties sso;
@Bean
public ResourceServerTokenServices userInfoTokenServices() {
return new AdfsUserInfoTokenServices(sso.getUserInfoUri(), sso.getClientId());
}
:https : //vcsjones.com/2015/05/04/authenticating-asp-net-5-to-ad-fs-
oauth/
您需要将依赖方信任的ID作为参数’resource’的值添加到属性文件userAuthorizationUri中。
如果您不想创建自己的PrincipalExtractor或AuthoritiesExtractor(请参阅AdfsUserInfoTokenServices代码),请设置用户名所使用的任何属性(例如SAM-
Account-Name),使其具有“发送方声明类型”和“用户名”
。在为组创建索赔规则时,请确保“索赔”类型为“权威”(ADFS只允许我输入该名称,没有该名称的现有索赔类型)。否则,您可以编写提取程序以使用ADFS声明类型。
完成所有操作后,您应该有一个有效的示例。这里有很多细节,但是一旦您掌握了它,还算不错(比让SAML与ADFS配合使用更容易)。关键是要了解ADFS在OAuth2令牌中嵌入数据的方式,以及如何使用UserInfoTokenServices对象。希望这对其他人有帮助。
以上是 如何为ADFS配置Spring Boot安全性OAuth2? 的全部内容, 来源链接: utcz.com/qa/429488.html