Merge pull request #39 from dBucik/acrs

Acrs
pull/1580/head
Dominik František Bučík 2021-11-19 16:18:08 +01:00 committed by GitHub
commit 9a0a0f173c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 137 additions and 160 deletions

View File

@ -86,6 +86,7 @@ CREATE TABLE IF NOT EXISTS authentication_holder_request_parameter (
CREATE TABLE IF NOT EXISTS saved_user_auth (
id BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 1) PRIMARY KEY,
acr VARCHAR(1024),
name VARCHAR(1024),
authenticated BOOLEAN,
source_class VARCHAR(2048)

View File

@ -85,6 +85,7 @@ CREATE TABLE IF NOT EXISTS authentication_holder_request_parameter (
CREATE TABLE IF NOT EXISTS saved_user_auth (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
acr VARCHAR(1024),
name VARCHAR(1024),
authenticated BOOLEAN,
source_class VARCHAR(2048)

View File

@ -86,6 +86,7 @@ CREATE TABLE IF NOT EXISTS authentication_holder_request_parameter (
CREATE TABLE IF NOT EXISTS saved_user_auth (
id BIGSERIAL PRIMARY KEY,
acr VARCHAR(1024),
name VARCHAR(1024),
authenticated BOOLEAN,
source_class VARCHAR(2048)

View File

@ -17,8 +17,10 @@
package cz.muni.ics.oauth2.model;
import cz.muni.ics.oauth2.model.convert.SimpleGrantedAuthorityStringConverter;
import cz.muni.ics.oidc.saml.SamlPrincipal;
import java.util.Collection;
import java.util.HashSet;
import java.util.stream.Collectors;
import javax.persistence.Basic;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
@ -32,8 +34,14 @@ import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Table;
import javax.persistence.Transient;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.opensaml.saml2.core.AuthnContext;
import org.opensaml.saml2.core.AuthnContextClassRef;
import org.opensaml.saml2.core.AuthnStatement;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.providers.ExpiringUsernameAuthenticationToken;
/**
* This class stands in for an original Authentication object.
@ -42,6 +50,8 @@ import org.springframework.security.core.GrantedAuthority;
*/
@Entity
@Table(name="saved_user_auth")
@Slf4j
@ToString
public class SavedUserAuthentication implements Authentication {
private static final long serialVersionUID = -1804249963940323488L;
@ -50,18 +60,21 @@ public class SavedUserAuthentication implements Authentication {
private String name;
private Collection<GrantedAuthority> authorities;
private boolean authenticated;
private String sourceClass;
private String acr;
public SavedUserAuthentication(Authentication src) {
setName(src.getName());
setAuthorities(new HashSet<>(src.getAuthorities()));
setAuthenticated(src.isAuthenticated());
if (src instanceof SavedUserAuthentication) {
// if we're copying in a saved auth, carry over the original class name
setSourceClass(((SavedUserAuthentication) src).getSourceClass());
} else {
setSourceClass(src.getClass().getName());
if (src instanceof ExpiringUsernameAuthenticationToken) {
ExpiringUsernameAuthenticationToken token = (ExpiringUsernameAuthenticationToken) src;
this.acr = ((SamlPrincipal) token.getPrincipal()).getSamlCredential()
.getAuthenticationAssertion()
.getAuthnStatements().stream()
.map(AuthnStatement::getAuthnContext)
.map(AuthnContext::getAuthnContextClassRef)
.map(AuthnContextClassRef::getAuthnContextClassRef)
.collect(Collectors.joining());
}
}
@ -85,6 +98,10 @@ public class SavedUserAuthentication implements Authentication {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name="saved_user_auth_authority", joinColumns=@JoinColumn(name="owner_id"))
@ -94,6 +111,32 @@ public class SavedUserAuthentication implements Authentication {
return authorities;
}
public void setAuthorities(Collection<GrantedAuthority> authorities) {
this.authorities = authorities;
}
@Basic
@Column(name = "acr")
public String getAcr() {
return acr;
}
public void setAcr(String acr) {
this.acr = acr;
}
@Override
@Basic
@Column(name="authenticated")
public boolean isAuthenticated() {
return authenticated;
}
@Override
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
this.authenticated = isAuthenticated;
}
@Override
@Transient
public Object getCredentials() {
@ -112,34 +155,4 @@ public class SavedUserAuthentication implements Authentication {
return getName();
}
@Override
@Basic
@Column(name="authenticated")
public boolean isAuthenticated() {
return authenticated;
}
@Override
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
this.authenticated = isAuthenticated;
}
@Basic
@Column(name="source_class")
public String getSourceClass() {
return sourceClass;
}
public void setSourceClass(String sourceClass) {
this.sourceClass = sourceClass;
}
public void setName(String name) {
this.name = name;
}
public void setAuthorities(Collection<GrantedAuthority> authorities) {
this.authorities = authorities;
}
}

View File

@ -33,6 +33,7 @@ import org.springframework.security.oauth2.common.exceptions.InvalidGrantExcepti
import org.springframework.security.oauth2.common.util.RandomValueStringGenerator;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.providers.ExpiringUsernameAuthenticationToken;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

View File

@ -22,6 +22,7 @@ import cz.muni.ics.oauth2.model.DeviceCode;
import cz.muni.ics.oauth2.service.DeviceCodeService;
import cz.muni.ics.oauth2.web.DeviceEndpoint;
import java.util.Date;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.ClientDetails;
@ -42,6 +43,7 @@ import org.springframework.stereotype.Component;
*
*/
@Component("deviceTokenGranter")
@Slf4j
public class DeviceTokenGranter extends AbstractTokenGranter {
public static final String GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";

View File

@ -243,8 +243,9 @@ public class DeviceEndpoint {
@PreAuthorize("hasRole('ROLE_USER')")
@RequestMapping(value = "/" + USER_URL + "/approve", method = RequestMethod.POST)
public String approveDevice(@RequestParam("user_code") String userCode, @RequestParam(value = "user_oauth_approval") Boolean approve, ModelMap model, Authentication auth, HttpSession session) {
public String approveDevice(@RequestParam("user_code") String userCode,
@RequestParam(value = "user_oauth_approval") Boolean approve,
ModelMap model, Authentication auth, HttpSession session) {
AuthorizationRequest authorizationRequest = (AuthorizationRequest) session.getAttribute("authorizationRequest");
DeviceCode dc = (DeviceCode) session.getAttribute("deviceCode");

View File

@ -30,8 +30,7 @@ public class PerunSamlAuthenticationProvider extends SAMLAuthenticationProvider
@Override
protected Object getPrincipal(SAMLCredential credential, Object userDetail) {
PerunUser user = (PerunUser) userDetail;
return new User(String.valueOf(user.getId()), credential.getRemoteEntityID(),
getEntitlements(credential, userDetail));
return new SamlPrincipal(user.getId(), credential, getEntitlements(credential, userDetail));
}
@Override

View File

@ -1,6 +1,5 @@
package cz.muni.ics.oidc.saml;
import cz.muni.ics.oidc.server.PerunPrincipal;
import cz.muni.ics.oidc.server.adapters.PerunAdapter;
import cz.muni.ics.oidc.server.filters.FiltersUtils;
import lombok.extern.slf4j.Slf4j;
@ -24,9 +23,7 @@ public class PerunSamlUserDetailsService implements SAMLUserDetailsService {
@Override
public Object loadUserBySAML(SAMLCredential credential) throws UsernameNotFoundException {
log.debug("Loading user for SAML credential");
PerunPrincipal p = FiltersUtils.getPerunPrincipal(credential, samlProperties.getUserIdentifierAttribute());
log.debug("Fetching user from perun ({})", p);
return perunAdapter.getPreauthenticatedUserId(p);
return FiltersUtils.getPerunUser(credential, perunAdapter, samlProperties.getUserIdentifierAttribute());
}
}

View File

@ -0,0 +1,27 @@
package cz.muni.ics.oidc.saml;
import java.util.Collection;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.saml.SAMLCredential;
@Getter
@Setter
@ToString
public class SamlPrincipal extends User {
private Long perunUserId;
private SAMLCredential samlCredential;
public SamlPrincipal(Long perunUserId,
SAMLCredential samlCredential,
Collection<? extends GrantedAuthority> authorities) {
super(String.valueOf(perunUserId), "[PROTECTED]", authorities);
this.perunUserId = perunUserId;
this.samlCredential = samlCredential;
}
}

View File

@ -18,9 +18,6 @@ import lombok.extern.slf4j.Slf4j;
import net.minidev.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* Modifies ID Token.
@ -49,8 +46,11 @@ public class PerunOIDCTokenService extends DefaultOIDCTokenService {
}
@Override
protected void addCustomIdTokenClaims(JWTClaimsSet.Builder idClaims, ClientDetailsEntity client, OAuth2Request request,
String sub, OAuth2AccessTokenEntity accessToken)
protected void addCustomIdTokenClaims(JWTClaimsSet.Builder idClaims,
ClientDetailsEntity client,
OAuth2Request request,
String sub,
OAuth2AccessTokenEntity accessToken)
{
log.debug("modifying ID token");
String userId = accessToken.getAuthenticationHolder().getAuthentication().getName();
@ -73,18 +73,17 @@ public class PerunOIDCTokenService extends DefaultOIDCTokenService {
}
}
String acr = getAuthnContextClass();
if (acr != null) {
log.debug("adding to ID token claim acr with value {}", acr);
idClaims.claim("acr", acr);
if (accessToken.getAuthenticationHolder() != null
&& accessToken.getAuthenticationHolder().getUserAuth() != null)
{
String acr = accessToken.getAuthenticationHolder().getUserAuth().getAcr();
if (acr != null) {
log.debug("adding to ID token claim acr with value {}", acr);
idClaims.claim("acr", acr);
}
}
}
private String getAuthnContextClass() {
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
return (String) attr.getAttribute(SESSION_PARAM_ACR, RequestAttributes.SCOPE_SESSION);
}
/**
* Converts claim values from com.google.gson.JsonElement to net.minidev.json.JSONObject or primitive value
*

View File

@ -1,35 +0,0 @@
package cz.muni.ics.oidc.server;
/**
* Principal specific for Perun user. User is identified by login (extLogin) and name
* of the external source (extSourceName) he/she used for login (usually identity provider).
*
* @author Martin Kuba <makub@ics.muni.cz>
*/
public class PerunPrincipal {
private final String extLogin;
private final String extSourceName;
public PerunPrincipal(String extLogin, String extSourceName) {
this.extLogin = extLogin;
this.extSourceName = extSourceName;
}
public String getExtLogin() {
return extLogin;
}
public String getExtSourceName() {
return extSourceName;
}
@Override
public String toString() {
return "PerunPrincipal{" +
"extLogin='" + extLogin + '\'' +
", extSourceName='" + extSourceName + '\'' +
'}';
}
}

View File

@ -6,7 +6,6 @@ import cz.muni.ics.oidc.models.PerunAttributeValue;
import cz.muni.ics.oidc.models.PerunUser;
import cz.muni.ics.oidc.models.Resource;
import cz.muni.ics.oidc.models.Vo;
import cz.muni.ics.oidc.server.PerunPrincipal;
import cz.muni.ics.oidc.server.connectors.Affiliation;
import java.util.Collection;
import java.util.List;
@ -26,10 +25,9 @@ public interface PerunAdapterMethods {
/**
* Fetch user based on his principal (extLogin and extSource) from Perun
*
* @param perunPrincipal principal of user
* @return PerunUser with id of found user
*/
PerunUser getPreauthenticatedUserId(PerunPrincipal perunPrincipal);
PerunUser getPreauthenticatedUserId(String extLogin, String extSourceName);
/**
* Fetch user attribute values

View File

@ -6,7 +6,6 @@ import cz.muni.ics.oidc.models.PerunAttributeValue;
import cz.muni.ics.oidc.models.PerunUser;
import cz.muni.ics.oidc.models.Resource;
import cz.muni.ics.oidc.models.Vo;
import cz.muni.ics.oidc.server.PerunPrincipal;
import cz.muni.ics.oidc.server.adapters.PerunAdapter;
import cz.muni.ics.oidc.server.connectors.Affiliation;
import java.util.Collection;
@ -23,12 +22,12 @@ import java.util.Set;
public class PerunAdapterImpl extends PerunAdapter {
@Override
public PerunUser getPreauthenticatedUserId(PerunPrincipal perunPrincipal) {
public PerunUser getPreauthenticatedUserId(String extLogin, String extSourceName) {
try {
return this.getAdapterPrimary().getPreauthenticatedUserId(perunPrincipal);
return this.getAdapterPrimary().getPreauthenticatedUserId(extLogin, extSourceName);
} catch (UnsupportedOperationException e) {
if (this.isCallFallback()) {
return this.getAdapterFallback().getPreauthenticatedUserId(perunPrincipal);
return this.getAdapterFallback().getPreauthenticatedUserId(extLogin, extSourceName);
} else {
throw e;
}

View File

@ -43,7 +43,6 @@ import cz.muni.ics.oidc.models.Resource;
import cz.muni.ics.oidc.models.Vo;
import cz.muni.ics.oidc.models.enums.PerunAttrValueType;
import cz.muni.ics.oidc.models.enums.PerunEntityType;
import cz.muni.ics.oidc.server.PerunPrincipal;
import cz.muni.ics.oidc.server.adapters.PerunAdapter;
import cz.muni.ics.oidc.server.adapters.PerunAdapterMethods;
import cz.muni.ics.oidc.server.adapters.PerunAdapterMethodsLdap;
@ -96,16 +95,10 @@ public class PerunAdapterLdap extends PerunAdapterWithMappingServices implements
this.oidcCheckMembershipAttr = oidcCheckMembershipAttr;
}
/**
* Fetch user based on his principal (extLogin and extSource) from Perun
*
* @param perunPrincipal principal of user
* @return PerunUser with id of found user
*/
@Override
public PerunUser getPreauthenticatedUserId(PerunPrincipal perunPrincipal) {
public PerunUser getPreauthenticatedUserId(String extLogin, String extSourceName) {
FilterBuilder filter = and(
equal(OBJECT_CLASS, PERUN_USER), equal(EDU_PERSON_PRINCIPAL_NAMES, perunPrincipal.getExtLogin())
equal(OBJECT_CLASS, PERUN_USER), equal(EDU_PERSON_PRINCIPAL_NAMES, extLogin)
);
SearchScope scope = SearchScope.ONELEVEL;
String[] attributes = new String[]{PERUN_USER_ID, GIVEN_NAME, SN};

View File

@ -27,7 +27,6 @@ import cz.muni.ics.oidc.models.Vo;
import cz.muni.ics.oidc.models.enums.MemberStatus;
import cz.muni.ics.oidc.models.enums.PerunEntityType;
import cz.muni.ics.oidc.models.mappers.RpcMapper;
import cz.muni.ics.oidc.server.PerunPrincipal;
import cz.muni.ics.oidc.server.adapters.PerunAdapter;
import cz.muni.ics.oidc.server.adapters.PerunAdapterMethods;
import cz.muni.ics.oidc.server.adapters.PerunAdapterMethodsRpc;
@ -85,13 +84,13 @@ public class PerunAdapterRpc extends PerunAdapterWithMappingServices implements
}
@Override
public PerunUser getPreauthenticatedUserId(PerunPrincipal perunPrincipal) {
public PerunUser getPreauthenticatedUserId(String extLogin, String extSourceName) {
if (!this.connectorRpc.isEnabled()) {
return null;
}
Map<String, Object> map = new LinkedHashMap<>();
map.put("extLogin", perunPrincipal.getExtLogin());
map.put("extSourceName", perunPrincipal.getExtSourceName());
map.put("extLogin", extLogin);
map.put("extSourceName", extSourceName);
JsonNode response = connectorRpc.post(USERS_MANAGER, "getUserByExtSourceNameAndExtLogin", map);
return RpcMapper.mapPerunUser(response);

View File

@ -8,7 +8,6 @@ import cz.muni.ics.oauth2.service.ClientDetailsEntityService;
import cz.muni.ics.oidc.models.Facility;
import cz.muni.ics.oidc.models.PerunAttributeValue;
import cz.muni.ics.oidc.models.PerunUser;
import cz.muni.ics.oidc.server.PerunPrincipal;
import cz.muni.ics.oidc.server.adapters.PerunAdapter;
import cz.muni.ics.oidc.server.configurations.FacilityAttrsConfig;
import cz.muni.ics.oidc.web.controllers.ControllerUtils;
@ -93,21 +92,30 @@ public class FiltersUtils {
return client;
}
/**
* Get Perun user
* @param request Request object
* @param perunAdapter Adapter of Perun interface
* @return Found PerunUser
*/
public static PerunUser getPerunUser(HttpServletRequest request, PerunAdapter perunAdapter, String samlIdAttribute) {
SAMLCredential samlCredential = getSamlCredential(request);
public static PerunUser getPerunUser(HttpServletRequest request,
PerunAdapter perunAdapter,
String samlIdAttribute)
{
return getPerunUser(getSamlCredential(request), perunAdapter, samlIdAttribute);
}
public static PerunUser getPerunUser(SAMLCredential samlCredential,
PerunAdapter perunAdapter,
String samlIdAttribute) {
if (perunAdapter == null) {
throw new IllegalArgumentException("Cannot fetch user, no adapter passed");
}
if (samlCredential == null) {
return null;
}
PerunPrincipal principal = getPerunPrincipal(samlCredential, samlIdAttribute);
log.debug("fetching Perun user with extLogin '{}' and extSourceName '{}'",
principal.getExtLogin(), principal.getExtSourceName());
return perunAdapter.getPreauthenticatedUserId(principal);
String extLogin = getExtLogin(samlCredential, samlIdAttribute);
String extSourceName = getExtSourceName(samlCredential);
if (!StringUtils.hasText(extLogin)) {
return null;
} else if (!StringUtils.hasText(extSourceName)) {
return null;
}
return perunAdapter.getPreauthenticatedUserId(extLogin, extSourceName);
}
public static SAMLCredential getSamlCredential(HttpServletRequest request) {
@ -118,7 +126,7 @@ public class FiltersUtils {
return (SAMLCredential) p.getCredentials();
}
public static PerunPrincipal getPerunPrincipal(SAMLCredential credential, String idAttribute) {
public static String getExtLogin(SAMLCredential credential, String idAttribute) {
if (credential == null) {
throw new IllegalArgumentException("No SAML credential passed");
} else if (!StringUtils.hasText(idAttribute)) {
@ -128,39 +136,14 @@ public class FiltersUtils {
if (identifierAttrOid == null) {
throw new IllegalStateException("SAML credentials has no value for attribute: " + idAttribute);
}
String extLogin = credential.getAttributeAsString(identifierAttrOid);
String extSourceName = credential.getRemoteEntityID();
return new PerunPrincipal(extLogin, extSourceName);
return credential.getAttributeAsString(identifierAttrOid);
}
/**
* Extract PerunPrincipal from request
* @param req request object
* @param proxyExtSourceName name of proxy
* @return extracted principal or null if not present
*/
public static PerunPrincipal extractPerunPrincipal(HttpServletRequest req, String proxyExtSourceName) {
String extLogin = null;
String remoteUser = req.getRemoteUser();
if (StringUtils.hasText(remoteUser)) {
extLogin = remoteUser;
} else if (req.getUserPrincipal() != null) {
extLogin = ((User)req.getUserPrincipal()).getUsername();
public static String getExtSourceName(SAMLCredential credential) {
if (credential == null) {
throw new IllegalArgumentException("No SAML credential passed");
}
PerunPrincipal principal = null;
log.error("{}", req.getUserPrincipal());
log.error("{}", req.getRemoteUser());
if (extLogin != null) {
principal = new PerunPrincipal(extLogin, proxyExtSourceName);
log.debug("extracted principal '{}'", principal);
} else {
log.debug("could not extract principal");
}
return principal;
return credential.getRemoteEntityID();
}
/**

View File

@ -66,7 +66,6 @@ import org.springframework.stereotype.Service;
* @author Amanda Anganes
*
*/
@Service
@Slf4j
public class DefaultOIDCTokenService implements OIDCTokenService {

View File

@ -44,7 +44,6 @@ import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Service;
@Service
@Slf4j
public class ConnectTokenEnhancer implements TokenEnhancer {