use of org.springframework.security.authentication.UsernamePasswordAuthenticationToken in project spring-security-oauth by spring-projects.
the class TokenEndpointAuthenticationFilter method extractCredentials.
/**
* If the incoming request contains user credentials in headers or parameters then extract them here into an
* Authentication token that can be validated later. This implementation only recognises password grant requests and
* extracts the username and password.
*
* @param request the incoming request, possibly with user credentials
* @return an authentication for validation (or null if there is no further authentication)
*/
protected Authentication extractCredentials(HttpServletRequest request) {
String grantType = request.getParameter("grant_type");
if (grantType != null && grantType.equals("password")) {
UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(request.getParameter("username"), request.getParameter("password"));
result.setDetails(authenticationDetailsSource.buildDetails(request));
return result;
}
return null;
}
use of org.springframework.security.authentication.UsernamePasswordAuthenticationToken in project spring-security-oauth by spring-projects.
the class ResourceOwnerPasswordTokenGranter method getOAuth2Authentication.
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters());
String username = parameters.get("username");
String password = parameters.get("password");
// Protect from downstream leaks of password
parameters.remove("password");
Authentication userAuth = new UsernamePasswordAuthenticationToken(username, password);
((AbstractAuthenticationToken) userAuth).setDetails(parameters);
try {
userAuth = authenticationManager.authenticate(userAuth);
} catch (AccountStatusException ase) {
//covers expired, locked, disabled cases (mentioned in section 5.2, draft 31)
throw new InvalidGrantException(ase.getMessage());
} catch (BadCredentialsException e) {
// If the username/password are wrong the spec says we should send 400/invalid grant
throw new InvalidGrantException(e.getMessage());
}
if (userAuth == null || !userAuth.isAuthenticated()) {
throw new InvalidGrantException("Could not authenticate user: " + username);
}
OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
return new OAuth2Authentication(storedOAuth2Request, userAuth);
}
use of org.springframework.security.authentication.UsernamePasswordAuthenticationToken in project midpoint by Evolveum.
the class SpringAuthenticationInjectorInterceptor method handleMessage.
@Override
public void handleMessage(SoapMessage message) throws Fault {
//Note: in constructor we have specified that we will be called after we have been successfully authenticated the user through WS-Security
//Now we will only set the Spring Authentication object based on the user found in the header
LOGGER.trace("Intercepted message: {}", message);
SOAPMessage saajSoapMessage = securityHelper.getSOAPMessage(message);
if (saajSoapMessage == null) {
LOGGER.error("No soap message in handler");
throw createFault(WSSecurityException.ErrorCode.FAILURE);
}
ConnectionEnvironment connEnv = ConnectionEnvironment.create(SchemaConstants.CHANNEL_WEB_SERVICE_URI);
String username = null;
try {
username = securityHelper.getUsernameFromMessage(saajSoapMessage);
LOGGER.trace("Attempt to authenticate user '{}'", username);
if (StringUtils.isBlank(username)) {
message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
securityHelper.auditLoginFailure(username, null, connEnv, "Empty username");
throw createFault(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
}
MidPointPrincipal principal;
try {
principal = userDetailsService.getPrincipal(username);
} catch (SchemaException e) {
LOGGER.debug("Access to web service denied for user '{}': schema error: {}", username, e.getMessage(), e);
message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
securityHelper.auditLoginFailure(username, null, connEnv, "Schema error: " + e.getMessage());
throw new Fault(e);
}
LOGGER.trace("Principal: {}", principal);
if (principal == null) {
message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
securityHelper.auditLoginFailure(username, null, connEnv, "No user");
throw createFault(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
}
// Account validity and credentials and all this stuff should be already checked
// in the password callback
Authentication authentication = new UsernamePasswordAuthenticationToken(principal, null);
SecurityContextHolder.getContext().setAuthentication(authentication);
String operationName;
try {
operationName = DOMUtil.getFirstChildElement(saajSoapMessage.getSOAPBody()).getLocalName();
} catch (SOAPException e) {
LOGGER.debug("Access to web service denied for user '{}': SOAP error: {}", username, e.getMessage(), e);
message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
securityHelper.auditLoginFailure(username, principal.getUser(), connEnv, "SOAP error: " + e.getMessage());
throw new Fault(e);
}
// AUTHORIZATION
boolean isAuthorized;
try {
isAuthorized = securityEnforcer.isAuthorized(AuthorizationConstants.AUTZ_WS_ALL_URL, AuthorizationPhaseType.REQUEST, null, null, null, null);
LOGGER.trace("Determined authorization for web service access (action: {}): {}", AuthorizationConstants.AUTZ_WS_ALL_URL, isAuthorized);
} catch (SchemaException e) {
LOGGER.debug("Access to web service denied for user '{}': schema error: {}", username, e.getMessage(), e);
message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
securityHelper.auditLoginFailure(username, principal.getUser(), connEnv, "Schema error: " + e.getMessage());
throw createFault(WSSecurityException.ErrorCode.FAILURE);
}
if (!isAuthorized) {
String action = QNameUtil.qNameToUri(new QName(AuthorizationConstants.NS_AUTHORIZATION_WS, operationName));
try {
isAuthorized = securityEnforcer.isAuthorized(action, AuthorizationPhaseType.REQUEST, null, null, null, null);
LOGGER.trace("Determined authorization for web service operation {} (action: {}): {}", operationName, action, isAuthorized);
} catch (SchemaException e) {
LOGGER.debug("Access to web service denied for user '{}': schema error: {}", username, e.getMessage(), e);
message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
securityHelper.auditLoginFailure(username, principal.getUser(), connEnv, "Schema error: " + e.getMessage());
throw createFault(WSSecurityException.ErrorCode.FAILURE);
}
}
if (!isAuthorized) {
LOGGER.debug("Access to web service denied for user '{}': not authorized", username);
message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
securityHelper.auditLoginFailure(username, principal.getUser(), connEnv, "Not authorized");
throw createFault(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
}
} catch (WSSecurityException e) {
LOGGER.debug("Access to web service denied for user '{}': security exception: {}", username, e.getMessage(), e);
message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
securityHelper.auditLoginFailure(username, null, connEnv, "Security exception: " + e.getMessage());
throw new Fault(e, e.getFaultCode());
} catch (ObjectNotFoundException e) {
LOGGER.debug("Access to web service denied for user '{}': object not found: {}", username, e.getMessage(), e);
message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
securityHelper.auditLoginFailure(username, null, connEnv, "No user");
throw createFault(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
}
// Avoid auditing login attempt again if the operation fails on internal authorization
message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
LOGGER.debug("Access to web service allowed for user '{}'", username);
}
use of org.springframework.security.authentication.UsernamePasswordAuthenticationToken in project midpoint by Evolveum.
the class PageAccountActivation method propagatePassword.
private void propagatePassword(AjaxRequestTarget target, Form<?> form) {
List<ShadowType> shadowsToActivate = getShadowsToActivate();
PasswordTextField passwordPanel = (PasswordTextField) form.get(createComponentPath(ID_PASSWORD));
String value = passwordPanel.getModelObject();
ConnectionEnvironment connEnv = ConnectionEnvironment.create(SchemaConstants.CHANNEL_GUI_USER_URI);
UsernamePasswordAuthenticationToken token;
try {
token = authenticationEvaluator.authenticate(connEnv, new PasswordAuthenticationContext(userModel.getObject().getName().getOrig(), value));
} catch (Exception ex) {
LOGGER.error("Failed to authenticate user, reason ", ex.getMessage());
getSession().error(getString("PageAccountActivation.authentication.failed"));
throw new RestartResponseException(PageAccountActivation.class, getPageParameters());
}
if (token == null) {
LOGGER.error("Failed to authenticate user");
getSession().error(getString("PageAccountActivation.authentication.failed"));
throw new RestartResponseException(PageAccountActivation.class, getPageParameters());
}
ProtectedStringType passwordValue = new ProtectedStringType();
passwordValue.setClearValue(value);
Collection<ObjectDelta<ShadowType>> passwordDeltas = new ArrayList<>(shadowsToActivate.size());
for (ShadowType shadow : shadowsToActivate) {
ObjectDelta<ShadowType> shadowDelta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, shadow.getOid(), SchemaConstants.PATH_PASSWORD_VALUE, getPrismContext(), passwordValue);
shadowDelta.addModificationReplaceProperty(ShadowType.F_LIFECYCLE_STATE, SchemaConstants.LIFECYCLE_PROPOSED);
passwordDeltas.add(shadowDelta);
}
OperationResult result = runPrivileged(new Producer<OperationResult>() {
@Override
public OperationResult run() {
OperationResult result = new OperationResult(OPERATION_ACTIVATE_SHADOWS);
Task task = createAnonymousTask(OPERATION_ACTIVATE_SHADOWS);
WebModelServiceUtils.save((Collection) passwordDeltas, null, result, task, PageAccountActivation.this);
return result;
}
});
result.recomputeStatus();
if (!result.isSuccess()) {
getSession().error(getString("PageAccountActivation.account.activation.failed"));
LOGGER.error("Failed to acitvate accounts, reason: {} ", result.getMessage());
target.add(getFeedbackPanel());
} else {
getSession().success(getString("PageAccountActivation.account.activation.successful"));
target.add(getFeedbackPanel());
activated = true;
}
target.add(PageAccountActivation.this);
}
use of org.springframework.security.authentication.UsernamePasswordAuthenticationToken in project midpoint by Evolveum.
the class MidPointAuthenticationProvider method authenticate.
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String enteredUsername = (String) authentication.getPrincipal();
LOGGER.trace("Authenticating username '{}'", enteredUsername);
ConnectionEnvironment connEnv = ConnectionEnvironment.create(SchemaConstants.CHANNEL_GUI_USER_URI);
Authentication token;
if (authentication instanceof UsernamePasswordAuthenticationToken) {
String enteredPassword = (String) authentication.getCredentials();
token = passwordAuthenticationEvaluator.authenticate(connEnv, new PasswordAuthenticationContext(enteredUsername, enteredPassword));
} else if (authentication instanceof PreAuthenticatedAuthenticationToken) {
token = passwordAuthenticationEvaluator.authenticateUserPreAuthenticated(connEnv, enteredUsername);
} else {
LOGGER.error("Unsupported authentication {}", authentication);
throw new AuthenticationServiceException("web.security.provider.unavailable");
}
MidPointPrincipal principal = (MidPointPrincipal) token.getPrincipal();
LOGGER.debug("User '{}' authenticated ({}), authorities: {}", authentication.getPrincipal(), authentication.getClass().getSimpleName(), principal.getAuthorities());
return token;
}
Aggregations