下面列出了org.springframework.security.core.Authentication#isAuthenticated ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication instanceof UsernamePasswordAuthenticationToken
&& authentication.isAuthenticated()
&& !authentication.getName().equals(ANONYMOUS_USERNAME)
&& !httpRequest.getRequestURI().equalsIgnoreCase(CHANGE_PASSWORD_URI)) {
User user = userService.getUser(authentication.getName());
if (user == null) {
throw new RuntimeException("Unknown username [" + authentication.getName() + "]");
}
if (user.isChangePassword() != null && user.isChangePassword()) {
redirectStrategy.sendRedirect(httpRequest, httpResponse, CHANGE_PASSWORD_URI);
return;
}
}
chain.doFilter(request, response);
}
private void authenticateIfPossible(ServletRequest request) {
if (!request.isSecure()) {
return;
}
X509Certificate[] certs = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
if (certs == null || certs.length == 0) {
if (logger.isDebugEnabled()) {
logger.debug("Unable to get certificates in request from " + HttpRequestUtil.getClientString(request));
}
return;
}
Authentication authentication = authenticationManager.authenticate(new X509AuthenticationToken(certs));
if (authentication.isAuthenticated()) {
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters());
String authorizationCode = parameters.get("authorizationCode");
String provider = parameters.get("provider");
Authentication userAuth = new AcAuthenticationToken(authorizationCode, provider);
((AbstractAuthenticationToken) userAuth).setDetails(parameters);
try {
userAuth = authenticationManager.authenticate(userAuth);
} catch (AccountStatusException | BadCredentialsException ase) {
//covers expired, locked, disabled cases (mentioned in section 5.2, draft 31)
throw new InvalidGrantException(ase.getMessage());
}
if (userAuth == null || !userAuth.isAuthenticated()) {
throw new InvalidGrantException("Could not authenticate user: " + authorizationCode);
}
OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
return new OAuth2Authentication(storedOAuth2Request, userAuth);
}
private void performLdapTest(FieldModel fieldModel, FieldAccessor registeredFieldValues) throws IntegrationException {
logger.info("LDAP enabled testing LDAP authentication.");
String userName = fieldModel.getFieldValue(AuthenticationUIConfig.TEST_FIELD_KEY_USERNAME).orElse("");
Optional<LdapAuthenticationProvider> ldapProvider = ldapManager.createAuthProvider(registeredFieldValues);
String errorMessage = String.format("Ldap Authentication test failed for the test user %s. Please check the LDAP configuration.", userName);
Map<String, String> errorsMap = new HashMap<>();
if (!ldapProvider.isPresent()) {
errorsMap.put(AuthenticationDescriptor.KEY_LDAP_ENABLED, errorMessage);
} else {
Authentication pendingAuthentication = new UsernamePasswordAuthenticationToken(userName,
fieldModel.getFieldValue(AuthenticationUIConfig.TEST_FIELD_KEY_PASSWORD).orElse(""));
Authentication authentication = ldapProvider.get().authenticate(pendingAuthentication);
if (!authentication.isAuthenticated()) {
errorsMap.put(AuthenticationDescriptor.KEY_LDAP_ENABLED, errorMessage);
}
authentication.setAuthenticated(false);
}
if (!errorsMap.isEmpty()) {
throw new AlertFieldException(errorsMap);
}
}
public String getCurrentAuditor() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String currentUser = "anonymousUser";
if (authentication != null && authentication.isAuthenticated()) {
Object principal = authentication.getPrincipal();
if (principal instanceof UserDetails) {
currentUser = ((UserDetails)principal).getUsername();
} else {
currentUser = principal.toString();
}
}
return currentUser;
}
@Override
public boolean hasPermission(Authentication authentication, Object target, Object permission) {
if (!authentication.isAuthenticated()) {
return true;
}
if (target instanceof Optional) {
target = ((Optional<?>) target).orElse(null);
}
if (target == null) {
return false;
}
CloudbreakUser cloudbreakUser = restRequestThreadLocalService.getCloudbreakUser();
Collection<?> targets = target instanceof Collection ? (Collection<?>) target : Collections.singleton(target);
return targets.stream().allMatch(t -> {
if (!(t instanceof Clustered)) {
return true;
}
Cluster cluster = ((Clustered) t).getCluster();
if (cluster == null || !cloudbreakUser.getTenant().contentEquals(cluster.getClusterPertain().getTenant())) {
return false;
}
cloudbreakAuthorizationService.hasAccess(cluster.getStackCrn(), cloudbreakUser.getUserId(), cloudbreakUser.getTenant(), permission.toString());
return true;
});
}
private boolean authenticationIsRequired(String username) {
Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
if (Objects.isNull(existingAuth) || !existingAuth.isAuthenticated()) {
return true;
}
if (existingAuth instanceof UsernamePasswordAuthenticationToken
&& !existingAuth.getName().equals(username)) {
return true;
}
if (existingAuth instanceof AnonymousAuthenticationToken) {
return true;
}
return false;
}
private void tryAuthenticate(Authentication requestAuth) {
Authentication authentication = authenticationManager.authenticate(requestAuth);
if (authentication == null || !authentication.isAuthenticated()) {
throw new InternalAuthenticationServiceException("Unable to authenticate user with provided credentials");
}
logger.debug("Successfully authenticated");
SecurityContextHolder.getContext().setAuthentication(authentication);
}
private boolean isRequestToSign() {
if (!Boolean.TRUE.equals(RequestContext.getCurrentContext().get(AUTHENTICATION_SCHEME_BY_PASS_KEY))) {
return false;
}
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) return false;
if (!(authentication.getCredentials() instanceof X509Certificate)) return false;
return authentication.isAuthenticated();
}
public boolean authenticate(String login, String password) {
try {
Authentication auth = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(login, password));
SecurityContextHolder.getContext().setAuthentication(auth);
return auth.isAuthenticated();
} catch (BadCredentialsException ex) {
// todo
return false;
}
}
private Authentication tryToAuthenticate(Authentication requestAuth) {
Authentication responseAuth = getAuthenticationManager().authenticate(requestAuth);
if (responseAuth == null || !responseAuth.isAuthenticated()) {
throw new InternalAuthenticationServiceException("Unable to authenticate Domain User for provided credentials");
}
log.debug("User successfully authenticated");
return responseAuth;
}
/**
* Determines if a user is already authenticated.
* @return
*/
private boolean authenticated() {
Authentication authentication = SecurityContextHolder.getContext()
.getAuthentication();
return authentication != null && authentication.isAuthenticated()
&& !(authentication instanceof AnonymousAuthenticationToken);
}
protected Authentication getValidAuthentication() {
SecurityContext ctx = getSecurityContext();
if (ctx != null) {
Authentication authc = ctx.getAuthentication();
if (authc != null && !(authc instanceof AnonymousAuthenticationToken) && authc.isAuthenticated()) {
return authc;
}
}
return null;
}
private boolean authenticationIsRequired(String username) {
// Only reauthenticate if username doesn't match SecurityContextHolder
// and user
// isn't authenticated
// (see SEC-53)
Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
if (existingAuth == null || !existingAuth.isAuthenticated()) {
return true;
}
// Limit username comparison to providers which use usernames (ie
// UsernamePasswordAuthenticationToken)
// (see SEC-348)
if (existingAuth instanceof UsernamePasswordAuthenticationToken && !existingAuth.getName().equals(username)) {
return true;
}
// Handle unusual condition where an AnonymousAuthenticationToken is
// already
// present
// This shouldn't happen very often, as BasicProcessingFitler is meant
// to be
// earlier in the filter
// chain than AnonymousAuthenticationFilter. Nevertheless, presence of
// both an
// AnonymousAuthenticationToken
// together with a BASIC authentication request header should indicate
// reauthentication using the
// BASIC protocol is desirable. This behaviour is also consistent with
// that
// provided by form and digest,
// both of which force re-authentication if the respective header is
// detected (and
// in doing so replace
// any existing AnonymousAuthenticationToken). See SEC-610.
if (existingAuth instanceof AnonymousAuthenticationToken) {
return true;
}
return false;
}
@Override
public void doFilter(ServletRequest rec, ServletResponse res, FilterChain chain) throws IOException,
ServletException {
HttpServletRequest request = (HttpServletRequest) rec;
HttpServletResponse response = (HttpServletResponse) res;
if (request.getAttribute(FILTER_APPLIED) != null) {
chain.doFilter(request, response);
return;
}
request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if ((authentication == null || (authentication != null && !authentication.isAuthenticated()))
&& "login".equals(request.getParameter("anonymous"))) {
String tenant = "default";
if (StringUtils.isNotEmpty(request.getParameter("tenant")))
tenant = request.getParameter("tenant");
ContextProperties config = Context.get().getProperties();
if (config.getBoolean(tenant + ".anonymous.enabled")) {
LDAuthenticationToken authToken = new LDAuthenticationToken(config.getProperty(tenant + ".anonymous.user"));
AuthenticationManager authenticationManager = (AuthenticationManager) Context.get().getBean(
AuthenticationManager.class);
try {
Authentication anonAuthentication = authenticationManager.authenticate(authToken);
if (anonAuthentication.isAuthenticated()) {
String sid = ((LDAuthenticationToken) anonAuthentication).getSid();
SessionManager.get().saveSid(request, response, sid);
}
} catch (AuthenticationException ae) {
} catch (Throwable t) {
log.error(t.getMessage(), t);
}
}
}
chain.doFilter(request, response);
}
@Override
public void authorize(Authentication authentication, UriInfo uriInfo) throws AuthorizationException {
if (authentication == null) {
throw new AuthorizationException("null authentication object provided.");
}
if (!authentication.isAuthenticated()) {
throw new AuthorizationException(authentication + " not authenticated.");
}
Set<String> authorities = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toSet());
String defaultAction = as(String.class, grantedAuthorityMap.getOrDefault(DEFAULT_ACTION, DENY));
String path = uriInfo.getAbsolutePath().getPath();
Map<String, Object> pathAuthorizations = as(Map.class, grantedAuthorityMap.get("Paths"));
if (pathAuthorizations == null && !ALLOW.equalsIgnoreCase(defaultAction)) {
throw new AuthorizationException("Didn't find authorizations for " + path + " and default policy is " + defaultAction + " instead of allow");
}
Map<String, Object> pathAuthorization = as(Map.class, pathAuthorizations.get(path));
if (pathAuthorization == null && !ALLOW.equalsIgnoreCase(defaultAction)) {
throw new AuthorizationException("Didn't find authorizations for " + path + " and default policy is " + defaultAction + " instead of allow");
}
defaultAction = as(String.class, pathAuthorization.getOrDefault(DEFAULT_ACTION, defaultAction));
List<Map<String, Object>> actions = as(List.class, pathAuthorization.get("Actions"));
MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
for (Map<String, Object> action : actions) {
String ruleAction = as(String.class, action.get("Action"));
if (ruleAction == null || !(ALLOW.equalsIgnoreCase(ruleAction) || DENY.equalsIgnoreCase(ruleAction))) {
throw new AuthorizationException("Expected Action key of allow or deny for " + action);
}
String authorization = as(String.class, action.get("Authorization"));
if (authorization != null && !authorities.contains(authorization)) {
continue;
}
Map<String, Object> parameters = as(Map.class, action.get("Query Parameters"));
if (parameters != null) {
boolean foundParameterMismatch = false;
for (Map.Entry<String, Object> parameter : parameters.entrySet()) {
Object value = parameter.getValue();
if (value instanceof String) {
value = Arrays.asList((String)value);
}
if (!Objects.equals(queryParameters.get(parameter.getKey()), value)) {
foundParameterMismatch = true;
break;
}
}
if (foundParameterMismatch) {
continue;
}
}
if (ALLOW.equalsIgnoreCase(ruleAction)) {
if (logger.isDebugEnabled()) {
logger.debug("Action " + action + "matched which resulted in " + ruleAction);
}
return;
} else {
throw new AuthorizationException("Action " + action + " matched which resulted in " + ruleAction);
}
}
if (ALLOW.equalsIgnoreCase(defaultAction)) {
if (logger.isDebugEnabled()) {
logger.debug("Found no matching actions so falling back to default action " + defaultAction);
}
} else {
throw new AuthorizationException("Didn't find authorizations for " + path + " and default policy is " + defaultAction + " instead of allow");
}
}
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
if (skipIfAlreadyAuthenticated) {
Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
if (existingAuth != null && existingAuth.isAuthenticated()
&& !(existingAuth instanceof AnonymousAuthenticationToken)) {
chain.doFilter(request, response);
return;
}
}
String header = request.getHeader("Authorization");
if ((header != null) && header.startsWith("Negotiate ")) {
if (logger.isDebugEnabled()) {
logger.debug("Received Negotiate Header for request " + request.getRequestURL() + ": " + header);
}
byte[] base64Token = header.substring(10).getBytes(StandardCharsets.UTF_8);
byte[] kerberosTicket = Base64.decode(base64Token);
KerberosServiceRequestToken authenticationRequest = new KerberosServiceRequestToken(kerberosTicket);
authenticationRequest.setDetails(authenticationDetailsSource.buildDetails(request));
Authentication authentication;
try {
authentication = authenticationManager.authenticate(authenticationRequest);
} catch (AuthenticationException e) {
//That shouldn't happen, as it is most likely a wrong
//configuration on the server side
logger.warn("Negotiate Header was invalid: " + header, e);
SecurityContextHolder.clearContext();
if (failureHandler != null) {
failureHandler.onAuthenticationFailure(request, response, e);
} else {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.flushBuffer();
}
return;
}
sessionStrategy.onAuthentication(authentication, request, response);
SecurityContextHolder.getContext().setAuthentication(authentication);
if (successHandler != null) {
successHandler.onAuthenticationSuccess(request, response, authentication);
}
}
chain.doFilter(request, response);
}
@SuppressWarnings("unchecked")
@Transactional
public <S extends T> S version(S currentVersion, VersionInfo info) {
Authentication authentication = auth.getAuthentication();
if (authentication == null || !authentication.isAuthenticated()) {
throw new SecurityException("no principal");
}
Object id = getId(currentVersion);
if (id == null) return null;
if (!isHead(currentVersion)) {
throw new LockingAndVersioningException("not head");
}
Principal lockOwner = lockingService.lockOwner(id);
if (lockOwner == null || !authentication.isAuthenticated() || authentication.getName().equals(lockOwner.getName()) == false) {
throw new LockOwnerException("not lock owner");
}
S newVersion = null;
if (!isPrivateWorkingCopy(currentVersion)) {
S ancestorRoot;
if (isAnestralRoot(currentVersion)) {
currentVersion = (S) versioner.establishAncestralRoot(currentVersion);
ancestorRoot = currentVersion;
}
else {
Object ancestorRootId = getAncestralRootId(currentVersion);
ancestorRoot = em.find((Class<S>) currentVersion.getClass(), ancestorRootId);
if (ancestorRoot == null) {
throw new LockingAndVersioningException(format("ancestor root not found: %s", ancestorRootId));
}
}
newVersion = (S) cloner.clone(currentVersion);
this.unlock(currentVersion);
newVersion = (S) versioner
.establishSuccessor(newVersion, info.getNumber(), info.getLabel(), ancestorRoot, currentVersion);
em.persist(newVersion);
Object newId = getId(newVersion);
newVersion = this.lock(newVersion);
newVersion = em.merge(newVersion);
} else {
newVersion = currentVersion;
BeanUtils.setFieldWithAnnotation(newVersion, VersionNumber.class, info.getNumber());
BeanUtils.setFieldWithAnnotation(newVersion, VersionLabel.class, info.getLabel());
newVersion = em.merge(newVersion);
currentVersion = (S) em.find(newVersion.getClass(), BeanUtils.getFieldWithAnnotation(newVersion, AncestorId.class));
this.unlock(currentVersion);
}
currentVersion = (S) versioner.establishAncestor(currentVersion, newVersion);
em.merge(currentVersion);
return newVersion;
}
private boolean isAuthenticated(Authentication authentication) {
return authentication != null && !(authentication instanceof AnonymousAuthenticationToken) && authentication.isAuthenticated();
}
@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
Authentication authenticationResult = authenticationManager
.authenticate(authentication);
if (authenticationResult.isAuthenticated()) {
// validates nonce because JWT is already valid
if (authentication instanceof PoPAuthenticationToken) {
PoPAuthenticationToken popAuthentication = (PoPAuthenticationToken) authentication;
// starts validating nonce here
String nonce = popAuthentication.getNonce();
if (nonce == null) {
throw new UnapprovedClientAuthenticationException(
"This request does not have a valid signed nonce");
}
String token = (String) popAuthentication.getPrincipal();
System.out.println("access token:" + token);
try {
JWT jwt = JWTParser.parse(token);
String publicKey = jwt.getJWTClaimsSet().getClaim("public_key").toString();
JWK jwk = JWK.parse(publicKey);
JWSObject jwsNonce = JWSObject.parse(nonce);
JWSVerifier verifier = new RSASSAVerifier((RSAKey) jwk);
if (!jwsNonce.verify(verifier)) {
throw new InvalidTokenException("Client hasn't possession of given token");
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
return authenticationResult;
}