org.springframework.security.core.Authentication#getName ( )源码实例Demo

下面列出了org.springframework.security.core.Authentication#getName ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@Override
protected void onLoginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication
    successfulAuthentication) {

    String login = successfulAuthentication.getName();

    log.debug("Creating new persistent login for user {}", login);
    PersistentToken token = userRepository.findOneByLogin(login).map(u -> {
        PersistentToken t = new PersistentToken();
        t.setSeries(RandomUtil.generateSeriesData());
        t.setUser(u);
        t.setTokenValue(RandomUtil.generateTokenData());
        t.setTokenDate(LocalDate.now());
        t.setIpAddress(request.getRemoteAddr());
        t.setUserAgent(request.getHeader("User-Agent"));
        return t;
    }).orElseThrow(() -> new UsernameNotFoundException("User " + login + " was not found in the database"));
    try {
        persistentTokenRepository.saveAndFlush(token);
        addCookie(token, request, response);
    } catch (DataAccessException e) {
        log.error("Failed to save persistent token ", e);
    }
}
 
/**
 * Get the {@link CalendarUser} by obtaining the currently logged in Spring Security user's
 * {@link Authentication#getName()} and using that to find the {@link CalendarUser} by email address (since for our
 * application Spring Security usernames are email addresses).
 */
@Override
public CalendarUser getCurrentUser() {
    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();
    if (authentication == null) {
        return null;
    }
    String email = authentication.getName();
    if (email == null) {
        return null;
    }
    CalendarUser result = calendarService.findUserByEmail(email);
    if (result == null) {
        throw new IllegalStateException(
                "Spring Security is not in synch with CalendarUsers. Could not find user with email " + email);
    }
    return result;
}
 
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = authentication.getName();
    String password;
    Map data = (Map) authentication.getDetails();
    String clientId = (String) data.get("client");
    Assert.hasText(clientId, "clientId must have value");
    String type = (String) data.get("type");
    Map map;

    password = (String) authentication.getCredentials();
    //如果你是调用user服务,这边不用注掉
    //map = userClient.checkUsernameAndPassword(getUserServicePostObject(username, password, type));
    map = checkUsernameAndPassword(getUserServicePostObject(username, password, type));


    String userId = (String) map.get("userId");
    if (StringUtils.isBlank(userId)) {
        String errorCode = (String) map.get("code");
        throw new BadCredentialsException(errorCode);
    }
    CustomUserDetails customUserDetails = buildCustomUserDetails(username, password, userId, clientId);
    return new CustomAuthenticationToken(customUserDetails);
}
 
源代码4 项目: java-starthere   文件: UseremailServiceImpl.java
@Override
public void delete(long id,
                   boolean isAdmin)
{
    if (useremailrepos.findById(id)
                      .isPresent())
    {
        Authentication authentication = SecurityContextHolder.getContext()
                                                             .getAuthentication();
        if (useremailrepos.findById(id)
                          .get()
                          .getUser()
                          .getUsername()
                          .equalsIgnoreCase(authentication.getName()) || isAdmin)
        {
            useremailrepos.deleteById(id);
        } else
        {
            throw new ResourceNotFoundException(authentication.getName() + " not authorized to make change");
        }
    } else
    {
        throw new ResourceNotFoundException("Useremail with id " + id + " Not Found!");
    }
}
 
源代码5 项目: fish-admin   文件: MatchPermissionEvaluator.java
@Override
public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {

    String userName = authentication.getName();
    User user = userRepository.findByUserName(userName);
    if (user == null)
        throw new UsernameNotFoundException("not found");
    // admin with id == 1
    if (user.isAdmin()) return true;

    Role role = roleRepository.find(user.getRoleId());
    if (role == null) return false;

    return role.hasPermission(targetDomainObject, permission);
}
 
源代码6 项目: Milkomeda   文件: Crust.java
/**
 * 从认证信息获取用户名
 *
 * @return 用户名
 */
public String getUsername() {
    Authentication authentication = getAuthentication();
    if (authentication != null) {
        return authentication.getName();
    }
    return null;
}
 
源代码7 项目: microservices-platform   文件: OauthTokenAspect.java
private String getClientId(Principal principal) {
    Authentication client = (Authentication) principal;
    if (!client.isAuthenticated()) {
        throw new InsufficientAuthenticationException("The client is not authenticated.");
    }
    String clientId = client.getName();
    if (client instanceof OAuth2Authentication) {
        clientId = ((OAuth2Authentication) client).getOAuth2Request().getClientId();
    }
    return clientId;
}
 
源代码8 项目: NFVO   文件: CustomUserDetailsService.java
@Override
public void changePassword(String oldPassword, String newPassword) {
  Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  String currentUserName = authentication.getName();
  log.debug("Changing password of user: " + currentUserName);
  User user = userRepository.findFirstByUsername(currentUserName);
  if (!BCrypt.checkpw(oldPassword, user.getPassword())) {
    throw new UnauthorizedUserException("Old password is wrong.");
  }
  if (!(authentication instanceof AnonymousAuthenticationToken)) { // TODO is this line needed?
    user.setPassword(BCrypt.hashpw(newPassword, BCrypt.gensalt(12)));
    userRepository.save(user);
    log.debug("Password of user " + currentUserName + " has been changed successfully.");
  }
}
 
private Authentication getADAuthentication(Authentication authentication) {
     try {
         String userName = authentication.getName();
         String userPassword = "";
         if (authentication.getCredentials() != null) {
             userPassword = authentication.getCredentials().toString();
         }

         ActiveDirectoryLdapAuthenticationProvider adAuthenticationProvider =
                 new ActiveDirectoryLdapAuthenticationProvider(adDomain, adURL);
         adAuthenticationProvider.setConvertSubErrorCodesToExceptions(true);
adAuthenticationProvider.setUseAuthenticationRequestCredentials(true);

         if (userName != null && userPassword != null
                 && !userName.trim().isEmpty()
                 && !userPassword.trim().isEmpty()) {
             final List<GrantedAuthority> grantedAuths = getAuthorities(userName);
             final UserDetails principal = new User(userName, userPassword,
                     grantedAuths);
             final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(
                     principal, userPassword, grantedAuths);
             authentication = adAuthenticationProvider.authenticate(finalAuthentication);
             if(groupsFromUGI) {
                 authentication = getAuthenticationWithGrantedAuthorityFromUGI(authentication);
             }
             return authentication;
         } else {
             LOG.error("AD Authentication Failed userName or userPassword is null or empty");
             return null;
         }
     } catch (Exception e) {
         LOG.error("AD Authentication Failed:", e);
         return null;
     }
 }
 
源代码10 项目: lemon   文件: SpringSecurityListener.java
public void logCredentialExpired(ApplicationEvent event) throws Exception {
    AuthenticationFailureCredentialsExpiredEvent authenticationFailureCredentialsExpiredEvent = (AuthenticationFailureCredentialsExpiredEvent) event;
    Authentication authentication = authenticationFailureCredentialsExpiredEvent
            .getAuthentication();
    logger.info("logCredentialExpired : {}", authentication);

    String tenantId = this.getTenantId(authentication);

    Object principal = authentication.getPrincipal();
    String userId = null;

    if (principal instanceof SpringSecurityUserAuth) {
        userId = ((SpringSecurityUserAuth) principal).getId();
    } else {
        userId = authentication.getName();
    }

    AuditDTO auditDto = new AuditDTO();
    auditDto.setUserId(userId);
    auditDto.setAuditTime(new Date());
    auditDto.setAction("login");
    auditDto.setResult("failure");
    auditDto.setApplication("lemon");
    auditDto.setClient(getUserIp(authentication));
    auditDto.setServer(InetAddress.getLocalHost().getHostAddress());
    auditDto.setDescription(authenticationFailureCredentialsExpiredEvent
            .getException().getMessage());
    auditDto.setTenantId(tenantId);
    auditConnector.log(auditDto);

    ctx.publishEvent(new LoginEvent(authentication, userId, this
            .getSessionId(authentication), "credentialExpired", "default",
            tenantId));
}
 
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
    Principal userPrincipal = request.getUserPrincipal();
    if (userPrincipal != null && (userPrincipal instanceof Authentication)) {
        Authentication auth = (Authentication)userPrincipal;
        String authToken = (String) auth.getCredentials();
        AuthenticatedUser currentUser = new AuthenticatedUser(auth.getName(),
                authToken, extractAuthorities(userPrincipal));
        
        AuthenticationContextHolder.setAuthenticatedUser(currentUser);

        request.setAttribute(REQ_ATTR_KEY_CURRENT_USER, currentUser);
    }
    return true;
}
 
源代码12 项目: tutorials   文件: CustomAuthenticationProvider.java
@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    final String name = authentication.getName();
    final String password = authentication.getCredentials().toString();
    if (name.equals("admin") && password.equals("system")) {
        final List<GrantedAuthority> grantedAuths = new ArrayList<>();
        grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
        final UserDetails principal = new User(name, password, grantedAuths);
        final Authentication auth = new UsernamePasswordAuthenticationToken(principal, password, grantedAuths);
        return auth;
    } else {
        return null;
    }
}
 
源代码13 项目: springlets   文件: AuthenticationAuditorAware.java
/**
 * Returns the object which represents the selected element for identifying
 * the user who modifies registers of an entity.
 * 
 * @return object which represents the user or null if the user is not logged.
 */
@Override
public String getCurrentAuditor() {
  Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  if (authentication == null || !authentication.isAuthenticated()) {
    return null;
  }
  return authentication.getName();
}
 
源代码14 项目: pivotal-bank-demo   文件: TradeController.java
@RequestMapping(value = "/trade", method = RequestMethod.POST)
public String showTrade(Model model, @ModelAttribute("search") Search search) {
	logger.debug("/trade.POST - symbol: " + search.getName());
	
	//model.addAttribute("marketSummary", marketService.getMarketSummary());
	model.addAttribute("search", search);
	
	if (search.getName() == null || search.getName().equals("") ) {
		model.addAttribute("quotes", new ArrayList<Quote>());
	} else {
		List<Quote> newQuotes = getQuotes(search.getName());
		model.addAttribute("quotes", newQuotes);
	}
	//check if user is logged in!
	Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	if (!(authentication instanceof AnonymousAuthenticationToken)) {
	    String currentUserName = authentication.getName();
	    logger.debug("User logged in: " + currentUserName);
	    model.addAttribute("order", new Order());
	    
	    
	    //TODO: add portfolio and account summary.
	    try {
	    	model.addAttribute("portfolio",portfolioService.getPortfolio(currentUserName));
	    	model.addAttribute("accounts",accountService.getAccounts(currentUserName));
	    } catch (HttpServerErrorException e) {
	    	model.addAttribute("portfolioRetrievalError",e.getMessage());
	    }
	}
	
	return "trade";
}
 
源代码15 项目: ranger   文件: RangerAuthenticationProvider.java
private Authentication getADBindAuthentication(Authentication authentication) {
	try {
		String rangerADURL = PropertiesUtil.getProperty("ranger.ldap.ad.url", "");
		String rangerLdapADBase = PropertiesUtil.getProperty("ranger.ldap.ad.base.dn", "");
		String rangerADBindDN = PropertiesUtil.getProperty("ranger.ldap.ad.bind.dn", "");
		String rangerADBindPassword = PropertiesUtil.getProperty("ranger.ldap.ad.bind.password", "");
		String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER");
		String rangerLdapReferral = PropertiesUtil.getProperty("ranger.ldap.ad.referral", "follow");
		String rangerLdapUserSearchFilter = PropertiesUtil.getProperty("ranger.ldap.ad.user.searchfilter", "(sAMAccountName={0})");
		boolean rangerIsStartTlsEnabled = Boolean.valueOf(PropertiesUtil.getProperty(
				"ranger.ldap.starttls", "false"));
		String userName = authentication.getName();
		String userPassword = "";
		if (authentication.getCredentials() != null) {
			userPassword = authentication.getCredentials().toString();
		}

		LdapContextSource ldapContextSource = new DefaultSpringSecurityContextSource(rangerADURL);
		ldapContextSource.setUserDn(rangerADBindDN);
		ldapContextSource.setPassword(rangerADBindPassword);
		ldapContextSource.setReferral(rangerLdapReferral);
		ldapContextSource.setCacheEnvironmentProperties(true);
		ldapContextSource.setAnonymousReadOnly(false);
		ldapContextSource.setPooled(true);
		if (rangerIsStartTlsEnabled) {
			ldapContextSource.setPooled(false);
			ldapContextSource.setAuthenticationStrategy(new DefaultTlsDirContextAuthenticationStrategy());
		}
		ldapContextSource.afterPropertiesSet();

		//String searchFilter="(sAMAccountName={0})";
		if (rangerLdapUserSearchFilter==null || rangerLdapUserSearchFilter.trim().isEmpty()) {
			rangerLdapUserSearchFilter="(sAMAccountName={0})";
		}
		FilterBasedLdapUserSearch userSearch=new FilterBasedLdapUserSearch(rangerLdapADBase, rangerLdapUserSearchFilter,ldapContextSource);
		userSearch.setSearchSubtree(true);

		BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource);
		bindAuthenticator.setUserSearch(userSearch);
		bindAuthenticator.afterPropertiesSet();

		LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(bindAuthenticator);

		if (userName != null && userPassword != null && !userName.trim().isEmpty() && !userPassword.trim().isEmpty()) {
			final List<GrantedAuthority> grantedAuths = new ArrayList<>();
			grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole));
			final UserDetails principal = new User(userName, userPassword,grantedAuths);
			final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, userPassword, grantedAuths);

			authentication = ldapAuthenticationProvider.authenticate(finalAuthentication);
			authentication=getAuthenticationWithGrantedAuthority(authentication);
			return authentication;
		} else {
			return authentication;
		}
	} catch (Exception e) {
		logger.debug("AD Authentication Failed:", e);
	}
	return authentication;
}
 
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = authentication.getPrincipal() == null ? "NONE_PROVIDED" : authentication.getName();
    boolean cacheWasUsed = true;
    UserDetails user = this.userCache.getUserFromCache(username);
    if (user == null) {
        cacheWasUsed = false;

        try {
            user = this.retrieveUser(username, authentication);
        } catch (UsernameNotFoundException var6) {
            log.error("User \'" + username + "\' not found");
            if (this.hideUserNotFoundExceptions) {
                throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
            }

            throw var6;
        }

        Assert.notNull(user, "retrieveUser returned null - a violation of the interface contract");
    }

    try {
        this.preAuthenticationChecks.check(user);
        this.additionalAuthenticationChecks(user, authentication);
    } catch (AuthenticationException var7) {
        if (!cacheWasUsed) {
            throw var7;
        }

        cacheWasUsed = false;
        user = this.retrieveUser(username, authentication);
        this.preAuthenticationChecks.check(user);
        this.additionalAuthenticationChecks(user, authentication);
    }

    this.postAuthenticationChecks.check(user);
    if (!cacheWasUsed) {
        this.userCache.putUserInCache(user);
    }

    Object principalToReturn = user;
    if (this.forcePrincipalAsString) {
        principalToReturn = user.getUsername();
    }

    return this.createSuccessAuthentication(principalToReturn, authentication, user);
}
 
源代码17 项目: docs-manage   文件: DocsAuditorAware.java
@Override
public String getCurrentAuditor() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String username = authentication != null ? authentication.getName() : DocsConsts.DEV_USERNAME;
    return StringUtils.isBlank(username) ? DocsConsts.DEV_USERNAME : username;
}
 
源代码18 项目: ranger   文件: RangerAuthenticationProvider.java
public Authentication getUnixAuthentication(Authentication authentication) {

		try {
			String rangerLdapDefaultRole = PropertiesUtil.getProperty(
					"ranger.ldap.default.role", "ROLE_USER");
			DefaultJaasAuthenticationProvider jaasAuthenticationProvider = new DefaultJaasAuthenticationProvider();
			String loginModuleName = "org.apache.ranger.authentication.unix.jaas.RemoteUnixLoginModule";
			LoginModuleControlFlag controlFlag = LoginModuleControlFlag.REQUIRED;
			Map<String, String> options = PropertiesUtil.getPropertiesMap();
			AppConfigurationEntry appConfigurationEntry = new AppConfigurationEntry(
					loginModuleName, controlFlag, options);
			AppConfigurationEntry[] appConfigurationEntries = new AppConfigurationEntry[] { appConfigurationEntry };
			Map<String, AppConfigurationEntry[]> appConfigurationEntriesOptions = new HashMap<String, AppConfigurationEntry[]>();
			appConfigurationEntriesOptions.put("SPRINGSECURITY",
					appConfigurationEntries);
			Configuration configuration = new InMemoryConfiguration(
					appConfigurationEntriesOptions);
			jaasAuthenticationProvider.setConfiguration(configuration);
			RoleUserAuthorityGranter authorityGranter = new RoleUserAuthorityGranter();
			RoleUserAuthorityGranter[] authorityGranters = new RoleUserAuthorityGranter[] { authorityGranter };
			jaasAuthenticationProvider.setAuthorityGranters(authorityGranters);
			jaasAuthenticationProvider.afterPropertiesSet();
			String userName = authentication.getName();
			String userPassword = "";
			if (authentication.getCredentials() != null) {
				userPassword = authentication.getCredentials().toString();
			}

			// getting user authenticated
			if (userName != null && userPassword != null
					&& !userName.trim().isEmpty()
					&& !userPassword.trim().isEmpty()) {
				final List<GrantedAuthority> grantedAuths = new ArrayList<>();
				grantedAuths.add(new SimpleGrantedAuthority(
						rangerLdapDefaultRole));
				final UserDetails principal = new User(userName, userPassword,
						grantedAuths);
				final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(
						principal, userPassword, grantedAuths);
				authentication = jaasAuthenticationProvider
						.authenticate(finalAuthentication);
				authentication=getAuthenticationWithGrantedAuthority(authentication);
				return authentication;
			} else {
				return authentication;
			}
		} catch (Exception e) {
			logger.debug("Unix Authentication Failed:", e);
		}

		return authentication;
	}
 
源代码19 项目: docs-manage   文件: DocsAuditorAware.java
@Override
public String getCurrentAuditor() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String username = authentication != null ? authentication.getName() : DocsConsts.DEV_USERNAME;
    return StringUtils.isBlank(username) ? DocsConsts.DEV_USERNAME : username;
}
 
源代码20 项目: atlas   文件: AtlasPamAuthenticationProvider.java
private Authentication getPamAuthentication(Authentication authentication) {
    if (isDebugEnabled) {
        LOG.debug("==> AtlasPamAuthenticationProvider getPamAuthentication");
    }
    try {
        String userName = authentication.getName();
        String userPassword = "";
        if (authentication.getCredentials() != null) {
            userPassword = authentication.getCredentials().toString();
        }

        // getting user authenticated
        if (userName != null && userPassword != null
                && !userName.trim().isEmpty()
                && !userPassword.trim().isEmpty()) {
            final List<GrantedAuthority> grantedAuths = getAuthorities(userName);

            final UserDetails principal = new User(userName, userPassword,
                    grantedAuths);

            final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(
                    principal, userPassword, grantedAuths);

            authentication = jaasAuthenticationProvider
                    .authenticate(finalAuthentication);

            if(groupsFromUGI) {
                authentication = getAuthenticationWithGrantedAuthorityFromUGI(authentication);
            } else {
                authentication = getAuthenticationWithGrantedAuthority(authentication);
            }
            return authentication;
        } else {
            return authentication;
        }

    } catch (Exception e) {
        LOG.debug("Pam Authentication Failed:", e);
    }
    if (isDebugEnabled) {
        LOG.debug("<== AtlasPamAuthenticationProvider getPamAuthentication : " + jaasAuthenticationProvider);
    }
    return authentication;
}