如何为ADFS配置Spring Boot安全性OAuth2?

时间:2017-03-31 19:44:56

标签: java spring spring-mvc spring-boot spring-security

是否有人使用ADFS成功配置Spring Boot OAuth2作为身份提供商?我成功地使用了本教程for 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?]

4 个答案:

答案 0 :(得分:6)

tldr; ADFS将用户信息嵌入到oauth令牌中。您需要创建并覆盖org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoTokenServices对象以提取此信息并将其添加到Principal对象

要开始使用,请先关注Spring OAuth2教程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/

将此添加到您的配置中:

@Autowired
private ResourceServerProperties sso;

@Bean
public ResourceServerTokenServices userInfoTokenServices() {
    return new AdfsUserInfoTokenServices(sso.getUserInfoUri(), sso.getClientId());
}

现在按照这些说明的第一部分来设置ADFS客户端和依赖方信任https://vcsjones.com/2015/05/04/authenticating-asp-net-5-to-ad-fs-oauth/

您需要将依赖方信任的ID添加到属性文件userAuthorizationUri作为参数“resource”的值。

声明规则:

如果您不想创建自己的PrincipalExtractor或AuthoritiesExtractor(请参阅AdfsUserInfoTokenServices代码),请设置您用于用户名的任何属性(例如SAM-Account-Name),以便它具有和Outgoing Claim Type '用户名'。在为组创建声明规则时,请确保声明类型是“权限”(ADFS只是让我输入,因此没有该名称的现有声明类型)。否则,您可以编写提取器以使用ADFS声明类型。

一旦完成,你应该有一个有效的例子。这里有很多细节,但一旦你把它弄下来,它就不会太糟糕(比让SAML与ADFS一起工作更容易)。关键是要了解ADFS在OAuth2令牌中嵌入数据的方式,并了解如何使用UserInfoTokenServices对象。希望这有助于其他人。

答案 1 :(得分:1)

除了已接受的答案:

@Ashika想知道您是否可以在REST而不是表单登录中使用它。 只需从@ EnableOAuth2Sso切换到@EnableResourceServer批注即可。

使用@EnableResourceServer批注,尽管您没有使用@ EnableOAuth2Sso批注,但仍可保持使用SSO的便利性。您正在作为资源服务器运行。

https://docs.spring.io/spring-security-oauth2-boot/docs/current/reference/htmlsingle/#boot-features-security-oauth2-resource-server

答案 2 :(得分:0)

尽管这个问题很古老,但网络上没有其他参考资料介绍如何将Spring OAuth2与ADFS集成。

因此,我添加了一个示例项目,说明如何使用Oauth2客户端的现成的Spring Boot自动配置与Microsoft ADFS集成:

https://github.com/selvinsource/spring-security/tree/oauth2login-adfs-sample/samples/boot/oauth2login#adfs-login

答案 3 :(得分:0)

@Erik,这是一个非常好的解释,说明如何将ADFS用作身份和授权提供者。我偶然发现的事情是在JWT令牌中获取“upn”和“email”信息。这是我收到的解码后的JWT信息 -

$scope = array('https://www.googleapis.com/auth/youtube.upload', 'https://www.googleapis.com/auth/youtube');
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setAccessToken('ya29.GlyKBK9LdtYRLNDYUdhXlhTiY_d51nLUZrIdikYoRY3M_5YQOpt5Pkx-uJ1RYpsvPOKyf4hTNBhKwOJ_fEncTURyNBeZa9ISRoVAmcuFaAlI_YgcQAs97GCbHklvXg');
$client->setScopes($scope);

$youtube = new Google_Service_YouTube($client);

// Check if an auth token exists for the required scopes
$tokenSessionKey = 'token-' . $client->prepareScopes();
if (isset($_GET['code'])) {
  if (strval($_SESSION['state']) !== strval($_GET['state'])) {
    die('The session state did not match.');
  }

  $client->authenticate($_GET['code']);
  $_SESSION[$tokenSessionKey] = $client->getAccessToken();
  header('Location: ' . $redirect);
}

if (isset($_SESSION[$tokenSessionKey])) {
  $client->setAccessToken($_SESSION[$tokenSessionKey]);
}

但是在“Issuance Transform Rules”下添加了email-id和upn并添加“将LDAP属性作为声明发送”声明规则将User-Principal-Name作为user_id发送(在PRINCIPAL_KETS上发布了FixedPrincipalExtractor - Spring security)我能够记录用于在我的UI应用程序上登录的user_id。以下是添加声明规则的已解码JWT帖子 -

2017-07-13 19:43:15.548  INFO 3848 --- [nio-8080-exec-7] c.e.demo.AdfsUserInfoTokenServices       : Decoded JWT: {"aud":"http://localhost:8080/web-app","iss":"http://adfs1.example.com/adfs/services/trust","iat":1500000192,"exp":1500003792,"apptype":"Confidential","appid":"1fd9b444-8ba4-4d82-942e-91aaf79f5fd0","authmethod":"urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport","auth_time":"2017-07-14T02:43:12.570Z","ver":"1.0"}