use of org.springframework.security.oauth2.common.exceptions.UnauthorizedUserException in project powerauth-webflow by wultra.
the class UserProfileController method userInfo.
/**
* Returns user profile of authenticated user, or anonymous user in case there is an error fetching user details.
* This method returns a minimal format compatible with OpenID Connect specification (basic JWT claims).
*
* @param authentication Original authentication of the currently logged user.
* @return User profile.
*/
@RequestMapping(value = "me/info", method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public UserInfoResponse userInfo(OAuth2Authentication authentication) {
// Try to fetch user details from the service
try {
final String usedId = authentication.getUserAuthentication().getName();
// Get additional information stored with the token
final Map<String, Object> additionalInfo = tokenServices.getAccessToken(authentication).getAdditionalInformation();
final String organizationId = (String) additionalInfo.get(ORGANIZATION_ID);
logger.info("Fetching user details for user with ID: {}, organization ID: {}", usedId, organizationId);
final ObjectResponse<UserDetailResponse> userDetail = client.fetchUserDetail(usedId, organizationId);
if (userDetail.getResponseObject().getAccountStatus() != AccountStatus.ACTIVE) {
return new UserInfoResponse(ANONYMOUS_USER, null, null, null, null);
}
final UserDetailResponse user = userDetail.getResponseObject();
final String id = user.getId();
final String givenName = user.getGivenName();
final String familyName = user.getFamilyName();
final Map<String, Object> extras = user.getExtras();
logger.info("Found user with ID: {}, given name: {}, family name: {}", usedId, givenName, familyName);
return new UserInfoResponse(id, id, givenName, familyName, extras);
} catch (DataAdapterClientErrorException e) {
throw new UnauthorizedUserException("Unable to fetch user details from data adapter");
}
}
use of org.springframework.security.oauth2.common.exceptions.UnauthorizedUserException in project resource-catalogue by madgeek-arc.
the class ApiKeyAuthorizationFilter method doFilter.
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
log.debug("Attempt Authentication");
HttpServletRequest request = (HttpServletRequest) req;
String jwt = resolveToken(request);
PendingOIDCAuthenticationToken token;
try {
if (jwt == null) {
throw new NullPointerException("jwt is null");
}
JWT idToken = JWTParser.parse(jwt);
String issuer = idToken.getJWTClaimsSet().getIssuer();
String subject = idToken.getJWTClaimsSet().getSubject();
String accessToken = idToken.getParsedString();
ServerConfiguration config = serverConfigurationService.getServerConfiguration(issuer);
token = new PendingOIDCAuthenticationToken(subject, issuer, config, idToken, accessToken, null);
Authentication auth = this.authenticationProvider.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(auth);
chain.doFilter(req, res);
} catch (RuntimeException | ParseException e) {
log.error(e);
res.setContentType(MediaType.APPLICATION_JSON_VALUE);
ObjectMapper mapper = new ObjectMapper();
UnauthorizedUserException exception = new UnauthorizedUserException(e.getMessage(), e);
res.getWriter().append(mapper.writeValueAsString(exception));
((HttpServletResponse) res).setStatus(401);
}
}
use of org.springframework.security.oauth2.common.exceptions.UnauthorizedUserException in project smartcampus.gamification by smartcommunitylab.
the class ProfileController method completeUserDetails.
private AuthUser completeUserDetails() {
AuthUser user;
if (SecurityContextHolder.getContext().getAuthentication().isAuthenticated() && SecurityContextHolder.getContext().getAuthentication().getPrincipal() != null) {
user = new AuthUser();
user.setUsername(SecurityContextHolder.getContext().getAuthentication().getName());
for (GrantedAuthority auth : SecurityContextHolder.getContext().getAuthentication().getAuthorities()) {
user.getDomains().add(auth.getAuthority().toString());
}
} else {
logger.info("Principal not found");
throw new UnauthorizedUserException("Principal not found");
}
return user;
}
use of org.springframework.security.oauth2.common.exceptions.UnauthorizedUserException in project resource-catalogue by madgeek-arc.
the class EICAuthoritiesMapper method mapAuthorities.
@Override
public Collection<? extends GrantedAuthority> mapAuthorities(JWT idToken, UserInfo userInfo) {
Set<GrantedAuthority> out = new HashSet<>();
if (idToken == null || userInfo == null) {
throw new UnauthorizedUserException("token is not valid or it has expired");
}
SimpleGrantedAuthority authority;
out.add(new SimpleGrantedAuthority("ROLE_USER"));
if (userRolesMap.get(userInfo.getSub()) != null) {
if (userRolesMap.get(userInfo.getEmail()) != null) {
// if there is also an email entry then user must be admin
authority = userRolesMap.get(userInfo.getEmail().toLowerCase());
} else {
authority = userRolesMap.get(userInfo.getSub());
}
} else {
authority = userRolesMap.get(userInfo.getEmail().toLowerCase());
}
if (authority != null) {
out.add(authority);
}
String authoritiesString = out.stream().map(GrantedAuthority::getAuthority).collect(Collectors.joining(","));
logger.info("User '{}' with email '{}' mapped as '{}'", userInfo.getSub(), userInfo.getEmail(), authoritiesString);
return out;
}
use of org.springframework.security.oauth2.common.exceptions.UnauthorizedUserException in project sw360 by eclipse.
the class KeycloakAccessTokenConverter method extractAuthentication.
/**
* Expects a token which has the keycloak format.
* The token contains a resource_access claim which is a list of resources and the granted roles on this resources.
* The expectation is that the token has resource client roles (WRITE/READ) of the sw360-REST-API client.
* INFO: the SecurityContextHolder.getContext().getAuthentication().getPrincipal(); will return user_name of the jwt
* @param tokenMap the raw jwt token
* @return the processed OAuth2Authentication
*/
@Override
@SuppressWarnings("unchecked")
public OAuth2Authentication extractAuthentication(Map<String, ?> tokenMap) {
log.debug("extract authentication: tokenMap = " + tokenMap.toString());
Map<String, Object> jwtToken = (Map<String, Object>) tokenMap;
// Map the roles of resource_access.sw360-REST-API.roles.* into authorities.*
if (tokenMap.containsKey(JWT_RESOURCE_ACCESS)) {
Map<String, Object> resourceAccess = (Map<String, Object>) jwtToken.get(JWT_RESOURCE_ACCESS);
if (resourceAccess.containsKey(resourceServerProperties.getResourceId())) {
Map<String, Object> clientAccess = (Map<String, Object>) resourceAccess.get(resourceServerProperties.getResourceId());
if (clientAccess.containsKey(JWT_ROLES)) {
ArrayList<String> clientRoles = (ArrayList<String>) clientAccess.get(JWT_ROLES);
jwtToken.put(JWT_AUTHORITIES, Collections.unmodifiableList(clientRoles));
}
}
}
// TODO: Right now only the userId is present in the session. But it may not exists in the database.
// implement user creation/mapping here. So new users in keycloak can directly query the restapi without liferay
// The idea is to create the users on the fly if they do no exist.
// based on the keycloak token which contains, name, surename and deparment already
// !!! -> This needs to be done with care.
// 1. Consider caching to avoid a lot of calls for the user object
// 2. Consider caching only for as long the token is the same to ensure valid user info
// User user = new User();
// user.setId("test2");
// authentication.setDetails(user);
Object userEmail = tokenMap.get("user_name");
if (userEmail != null && CommonUtils.isNotNullEmptyOrWhitespace(userEmail.toString())) {
String userEmailStr = userEmail.toString();
User sw360User = userService.getUserByEmail(userEmailStr);
if (sw360User == null || sw360User.isDeactivated()) {
throw new UnauthorizedUserException("User is deactivated");
}
}
return super.extractAuthentication(jwtToken);
}
Aggregations