use of java.security.Principal in project cas by apereo.
the class PrincipalFromRequestUserPrincipalNonInteractiveCredentialsAction method constructCredentialsFromRequest.
@Override
protected Credential constructCredentialsFromRequest(final RequestContext context) {
final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
final Principal principal = request.getUserPrincipal();
if (principal != null) {
LOGGER.debug("UserPrincipal [{}] found in HttpServletRequest", principal.getName());
return new PrincipalBearingCredential(this.principalFactory.createPrincipal(principal.getName()));
}
LOGGER.debug("UserPrincipal not found in HttpServletRequest.");
return null;
}
use of java.security.Principal in project gitblit by gitblit.
the class AuthenticationManager method authenticate.
/**
* Authenticate a user based on HTTP request parameters.
*
* Authentication by custom HTTP header, servlet container principal, X509Certificate, cookie,
* and finally BASIC header.
*
* @param httpRequest
* @param requiresCertificate
* @return a user object or null
*/
@Override
public UserModel authenticate(HttpServletRequest httpRequest, boolean requiresCertificate) {
// Check if this request has already been authenticated, and trust that instead of re-processing
String reqAuthUser = (String) httpRequest.getAttribute(Constants.ATTRIB_AUTHUSER);
if (!StringUtils.isEmpty(reqAuthUser)) {
logger.debug("Called servlet authenticate when request is already authenticated.");
return userManager.getUserModel(reqAuthUser);
}
// try to authenticate by servlet container principal
if (!requiresCertificate) {
Principal principal = httpRequest.getUserPrincipal();
if (principal != null) {
String username = principal.getName();
if (!StringUtils.isEmpty(username)) {
boolean internalAccount = userManager.isInternalAccount(username);
UserModel user = userManager.getUserModel(username);
if (user != null) {
// existing user
flagRequest(httpRequest, AuthenticationType.CONTAINER, user.username);
logger.debug(MessageFormat.format("{0} authenticated by servlet container principal from {1}", user.username, httpRequest.getRemoteAddr()));
return validateAuthentication(user, AuthenticationType.CONTAINER);
} else if (settings.getBoolean(Keys.realm.container.autoCreateAccounts, false) && !internalAccount) {
// auto-create user from an authenticated container principal
user = new UserModel(username.toLowerCase());
user.displayName = username;
user.password = Constants.EXTERNAL_ACCOUNT;
user.accountType = AccountType.CONTAINER;
// Try to extract user's informations for the session
// it uses "realm.container.autoAccounts.*" as the attribute name to look for
HttpSession session = httpRequest.getSession();
String emailAddress = resolveAttribute(session, Keys.realm.container.autoAccounts.emailAddress);
if (emailAddress != null) {
user.emailAddress = emailAddress;
}
String displayName = resolveAttribute(session, Keys.realm.container.autoAccounts.displayName);
if (displayName != null) {
user.displayName = displayName;
}
String userLocale = resolveAttribute(session, Keys.realm.container.autoAccounts.locale);
if (userLocale != null) {
user.getPreferences().setLocale(userLocale);
}
String adminRole = settings.getString(Keys.realm.container.autoAccounts.adminRole, null);
if (adminRole != null && !adminRole.isEmpty()) {
if (httpRequest.isUserInRole(adminRole)) {
user.canAdmin = true;
}
}
userManager.updateUserModel(user);
flagRequest(httpRequest, AuthenticationType.CONTAINER, user.username);
logger.debug(MessageFormat.format("{0} authenticated and created by servlet container principal from {1}", user.username, httpRequest.getRemoteAddr()));
return validateAuthentication(user, AuthenticationType.CONTAINER);
} else if (!internalAccount) {
logger.warn(MessageFormat.format("Failed to find UserModel for {0}, attempted servlet container authentication from {1}", principal.getName(), httpRequest.getRemoteAddr()));
}
}
}
}
// try to authenticate by certificate
boolean checkValidity = settings.getBoolean(Keys.git.enforceCertificateValidity, true);
String[] oids = settings.getStrings(Keys.git.certificateUsernameOIDs).toArray(new String[0]);
UserModel model = HttpUtils.getUserModelFromCertificate(httpRequest, checkValidity, oids);
if (model != null) {
// grab real user model and preserve certificate serial number
UserModel user = userManager.getUserModel(model.username);
X509Metadata metadata = HttpUtils.getCertificateMetadata(httpRequest);
if (user != null) {
flagRequest(httpRequest, AuthenticationType.CERTIFICATE, user.username);
logger.debug(MessageFormat.format("{0} authenticated by client certificate {1} from {2}", user.username, metadata.serialNumber, httpRequest.getRemoteAddr()));
return validateAuthentication(user, AuthenticationType.CERTIFICATE);
} else {
logger.warn(MessageFormat.format("Failed to find UserModel for {0}, attempted client certificate ({1}) authentication from {2}", model.username, metadata.serialNumber, httpRequest.getRemoteAddr()));
}
}
if (requiresCertificate) {
// caller requires client certificate authentication (e.g. git servlet)
return null;
}
UserModel user = null;
// try to authenticate by cookie
String cookie = getCookie(httpRequest);
if (!StringUtils.isEmpty(cookie)) {
user = userManager.getUserModel(cookie.toCharArray());
if (user != null) {
flagRequest(httpRequest, AuthenticationType.COOKIE, user.username);
logger.debug(MessageFormat.format("{0} authenticated by cookie from {1}", user.username, httpRequest.getRemoteAddr()));
return validateAuthentication(user, AuthenticationType.COOKIE);
}
}
// try to authenticate by BASIC
final String authorization = httpRequest.getHeader("Authorization");
if (authorization != null && authorization.startsWith("Basic")) {
// Authorization: Basic base64credentials
String base64Credentials = authorization.substring("Basic".length()).trim();
String credentials = new String(Base64.decode(base64Credentials), Charset.forName("UTF-8"));
// credentials = username:password
final String[] values = credentials.split(":", 2);
if (values.length == 2) {
String username = values[0];
char[] password = values[1].toCharArray();
user = authenticate(username, password, httpRequest.getRemoteAddr());
if (user != null) {
flagRequest(httpRequest, AuthenticationType.CREDENTIALS, user.username);
logger.debug(MessageFormat.format("{0} authenticated by BASIC request header from {1}", user.username, httpRequest.getRemoteAddr()));
return validateAuthentication(user, AuthenticationType.CREDENTIALS);
}
}
}
// Check each configured AuthenticationProvider
for (AuthenticationProvider ap : authenticationProviders) {
UserModel authedUser = ap.authenticate(httpRequest);
if (null != authedUser) {
flagRequest(httpRequest, ap.getAuthenticationType(), authedUser.username);
logger.debug(MessageFormat.format("{0} authenticated by {1} from {2} for {3}", authedUser.username, ap.getServiceName(), httpRequest.getRemoteAddr(), httpRequest.getPathInfo()));
return validateAuthentication(authedUser, ap.getAuthenticationType());
}
}
return null;
}
use of java.security.Principal in project hibernate-orm by hibernate.
the class StandardJaccServiceImpl method doPermissionCheckInContext.
private void doPermissionCheckInContext(PermissionCheckEntityInformation entityInformation, PermissibleAction action) {
final Policy policy = Policy.getPolicy();
final Principal[] principals = getCallerPrincipals();
final CodeSource codeSource = entityInformation.getEntity().getClass().getProtectionDomain().getCodeSource();
final ProtectionDomain pd = new ProtectionDomain(codeSource, null, null, principals);
// the action is known as 'method name' in JACC
final EJBMethodPermission jaccPermission = new EJBMethodPermission(entityInformation.getEntityName(), action.getImpliedActions()[0], null, null);
if (!policy.implies(pd, jaccPermission)) {
throw new SecurityException(String.format("JACC denied permission to [%s.%s] for [%s]", entityInformation.getEntityName(), action.getImpliedActions()[0], join(principals)));
}
}
use of java.security.Principal in project jaggery by wso2.
the class RequestHostObject method jsFunction_getUser.
public static String jsFunction_getUser(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws ScriptException {
String functionName = "getUser";
int argsCount = args.length;
if (argsCount != 0) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
RequestHostObject rho = (RequestHostObject) thisObj;
Principal principle = rho.request.getUserPrincipal();
if (principle == null) {
return null;
}
return principle.getName();
}
use of java.security.Principal in project XobotOS by xamarin.
the class JDKPKCS12KeyStore method engineGetCertificateChain.
public Certificate[] engineGetCertificateChain(String alias) {
if (alias == null) {
throw new IllegalArgumentException("null alias passed to getCertificateChain.");
}
if (!engineIsKeyEntry(alias)) {
return null;
}
Certificate c = engineGetCertificate(alias);
if (c != null) {
Vector cs = new Vector();
while (c != null) {
X509Certificate x509c = (X509Certificate) c;
Certificate nextC = null;
byte[] bytes = x509c.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId());
if (bytes != null) {
try {
ASN1InputStream aIn = new ASN1InputStream(bytes);
byte[] authBytes = ((ASN1OctetString) aIn.readObject()).getOctets();
aIn = new ASN1InputStream(authBytes);
AuthorityKeyIdentifier id = new AuthorityKeyIdentifier((ASN1Sequence) aIn.readObject());
if (id.getKeyIdentifier() != null) {
nextC = (Certificate) chainCerts.get(new CertId(id.getKeyIdentifier()));
}
} catch (IOException e) {
throw new RuntimeException(e.toString());
}
}
if (nextC == null) {
//
// no authority key id, try the Issuer DN
//
Principal i = x509c.getIssuerDN();
Principal s = x509c.getSubjectDN();
if (!i.equals(s)) {
Enumeration e = chainCerts.keys();
while (e.hasMoreElements()) {
X509Certificate crt = (X509Certificate) chainCerts.get(e.nextElement());
Principal sub = crt.getSubjectDN();
if (sub.equals(i)) {
try {
x509c.verify(crt.getPublicKey());
nextC = crt;
break;
} catch (Exception ex) {
// continue
}
}
}
}
}
cs.addElement(c);
if (// self signed - end of the chain
nextC != c) {
c = nextC;
} else {
c = null;
}
}
Certificate[] certChain = new Certificate[cs.size()];
for (int i = 0; i != certChain.length; i++) {
certChain[i] = (Certificate) cs.elementAt(i);
}
return certChain;
}
return null;
}
Aggregations