當前位置: 首頁>>代碼示例>>Java>>正文


Java Authentication.getDetails方法代碼示例

本文整理匯總了Java中org.springframework.security.core.Authentication.getDetails方法的典型用法代碼示例。如果您正苦於以下問題:Java Authentication.getDetails方法的具體用法?Java Authentication.getDetails怎麽用?Java Authentication.getDetails使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在org.springframework.security.core.Authentication的用法示例。


在下文中一共展示了Authentication.getDetails方法的14個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: getCurrentUserIp

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
/**
 * 取得當前用戶登錄IP, 如果當前用戶未登錄則返回空字符串.
 */
public static String getCurrentUserIp() {
    Authentication authentication = getAuthentication();

    if (authentication == null) {
        return "";
    }

    Object details = authentication.getDetails();

    if (!(details instanceof WebAuthenticationDetails)) {
        return "";
    }

    WebAuthenticationDetails webDetails = (WebAuthenticationDetails) details;

    return webDetails.getRemoteAddress();
}
 
開發者ID:zhaojunfei,項目名稱:lemon,代碼行數:21,代碼來源:SpringSecurityUtils.java

示例2: onAuthenticationSuccess

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
    String result = JSON.toJSONString(JsonUtil.getSuccessJsonObject(true));
    if (authentication != null && authentication.getDetails() != null) {
        try {
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            Map<String, Object> map = new HashMap<>();
            map.put("success", true);
            UserDetails userDetails = UserDetailsUtil.getCurrentUser();
            map.put("userDetails",userDetails);
            logger.info("FCat:userDetails:{}",userDetails);
            if(userDetails!=null) {
                SessionInfo sessionInfo = new SessionInfo();
                sessionInfo.setUsername(userDetails.getUsername());
                httpServletRequest.getSession().setAttribute("sessionInfo", sessionInfo);
                map.put("sessionInfo",sessionInfo);
            }
            HttpHelper.setResponseJsonData(httpServletResponse,JSON.toJSONString(JsonUtil.getSuccessJsonObject(map)));
            return ;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    HttpHelper.setResponseJsonData(httpServletResponse,result);
}
 
開發者ID:fier-liu,項目名稱:FCat,代碼行數:26,代碼來源:CustomAuthenticationSuccessHandler.java

示例3: authenticate

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (authentication.getDetails() instanceof ProxyCallbackAndServiceAuthenticationDetails &&
            getTicketValidator() instanceof Cas20ServiceTicketValidator) {
        String proxyCallbackUrl = ((ProxyCallbackAndServiceAuthenticationDetails) authentication.getDetails())
                .getProxyCallbackUrl();
        ((Cas20ServiceTicketValidator) getTicketValidator()).setProxyCallbackUrl(proxyCallbackUrl);
    }
    return super.authenticate(authentication);
}
 
開發者ID:kakawait,項目名稱:cas-security-spring-boot-starter,代碼行數:11,代碼來源:DynamicProxyCallbackUrlCasAuthenticationProvider.java

示例4: apply

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@Override
public void apply(RequestTemplate template) {
	if (!template.headers().containsKey(AUTH_HEADER)) {
		AitLogger.debug(logger, "Trying to assign the authorization token to the request header");
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		if (auth != null && auth.getDetails() instanceof OAuth2AuthenticationDetails) {
			OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) auth.getDetails();
			if (StringUtils.isEmpty(details.getTokenValue())) {
				AitLogger.warn(logger, "Empty token value.");
			} else {
				template.header(AUTH_HEADER, String.format("%s %s", BEARER, details.getTokenValue()));
			}
		} else {
			AitLogger.warn(logger, "Null or unknown authentication type object: {}", auth);
		}
	}
}
 
開發者ID:allianzit,項目名稱:ait-platform,代碼行數:18,代碼來源:AitApiClientInterceptor.java

示例5: Message

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
public Message(MessageType type, String message)
{
   this.type = type;
   this.message = message;

   SecurityContext context = SecurityContextHolder.getContext ();
   if (context == null)
   {
      return;
   }
   Authentication auth =
      SecurityContextHolder.getContext ().getAuthentication ();
   if (auth == null)
   {
      return;
   }
   String user;
   if (auth.getDetails () instanceof WebAuthenticationDetails)
   {
      WebAuthenticationDetails details =
            (WebAuthenticationDetails) auth.getDetails ();
      user = "["+((User)auth.getPrincipal ()).getUsername () +
            " @ "+details.getRemoteAddress ()+"] ";
   }
   else
   {
      user = "["+auth.getPrincipal ().toString () + "] ";
   }
   this.message = user + message;
}
 
開發者ID:SentinelDataHub,項目名稱:dhus-core,代碼行數:31,代碼來源:Message.java

示例6: getSessionId

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
public String getSessionId(Authentication authentication) {
    if (authentication == null) {
        return "";
    }

    Object details = authentication.getDetails();

    if (!(details instanceof WebAuthenticationDetails)) {
        return "";
    }

    WebAuthenticationDetails webDetails = (WebAuthenticationDetails) details;

    return webDetails.getSessionId();
}
 
開發者ID:zhaojunfei,項目名稱:lemon,代碼行數:16,代碼來源:LogoutSuccessHandlerImpl.java

示例7: getUserIp

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
public String getUserIp(Authentication authentication) {
    if (authentication == null) {
        return "";
    }

    Object details = authentication.getDetails();

    if (!(details instanceof WebAuthenticationDetails)) {
        return "";
    }

    WebAuthenticationDetails webDetails = (WebAuthenticationDetails) details;

    return webDetails.getRemoteAddress();
}
 
開發者ID:zhaojunfei,項目名稱:lemon,代碼行數:16,代碼來源:SpringSecurityListener.java

示例8: onLogoutSuccess

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@Override
public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                            Authentication authentication) throws IOException, ServletException {
  String result = JSON.toJSONString(JsonUtil.getSuccessJsonObject(true));
  logger.info("FCat result:{}",result);
  if (authentication != null && authentication.getDetails() != null) {
      try {
          httpServletRequest.getSession().invalidate();
          httpServletResponse.setStatus(HttpServletResponse.SC_OK);
      } catch (Exception e) {
          e.printStackTrace();
      }
  }
  HttpHelper.setResponseJsonData(httpServletResponse,result);
}
 
開發者ID:fier-liu,項目名稱:FCat,代碼行數:16,代碼來源:CustomLogoutSuccessHandler.java

示例9: authenticate

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@Override
@Transactional (propagation=Propagation.REQUIRED)
public Authentication authenticate (Authentication authentication)
   throws AuthenticationException
{
   String username = (String) authentication.getPrincipal ();
   String password = (String) authentication.getCredentials ();
   String ip = "unknown";
   String proxy = null;
   if (authentication.getDetails () instanceof WebAuthenticationDetails)
   {
      ip = ((WebAuthenticationDetails)authentication.getDetails ())
            .getRemoteAddress ();
   }
   if (authentication.getDetails() instanceof ProxyWebAuthenticationDetails)
   {
      String proxyAddress = ((ProxyWebAuthenticationDetails) authentication.getDetails()).getProxyAddress();
      if (proxyAddress != null)
      {
         proxy = " (proxy: " + proxyAddress + ")";
      }
   }

   LOGGER.info("Connection attempted by '{}' from {}",
         authentication.getName(), (proxy != null ? ip + proxy : ip));

   User user = userService.getUserNoCheck (username);
   if (user == null || user.isDeleted ())
   {
      throw new BadCredentialsException (errorMessage);
   }

   PasswordEncryption encryption = user.getPasswordEncryption ();
   if ( !encryption.equals (PasswordEncryption.NONE))
   {
      MessageDigest md;
      try
      {
         md = MessageDigest.getInstance (encryption.getAlgorithmKey ());
         password =
            new String (
                  Hex.encode (md.digest (password.getBytes ("UTF-8"))));
      }
      catch (NoSuchAlgorithmException | UnsupportedEncodingException e)
      {
         throw new BadCredentialsException ("Authentication process failed",
               e);
      }
   }

   if ( !user.getPassword ().equals (password))
   {
      LOGGER.warn (
            new Message (MessageType.USER, "Connection refused for '" +
                  username
                  + "' from " + ip +
                  " : error in login/password combination"));
      throw new BadCredentialsException (errorMessage);
   }
   
   for (AccessRestriction restriction : user.getRestrictions ())
   {
      LOGGER.warn ("Connection refused for '" + username +
            "' from " + ip + " : account is locked (" +
            restriction.getBlockingReason () + ")");
      throw new LockedException (restriction.getBlockingReason ());
   }
   
   LOGGER.info ("Connection success for '" + username + "' from " + ip);
   return new ValidityAuthentication (user, user.getAuthorities ());
}
 
開發者ID:SentinelDataHub,項目名稱:dhus-core,代碼行數:72,代碼來源:DefaultAuthenticationProvider.java

示例10: authenticate

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@Override
public Authentication authenticate(Authentication a) throws AuthenticationException {
    /**
     * Performing Timings of Authentication Interactions...
     */
    TimeDuration overall_duration = new TimeDuration();
    TimeDuration db_duration = new TimeDuration();
    TimeDuration pw_duration = new TimeDuration();

    overall_duration.start();
    String remoteIp = null;
    if (a.getDetails() != null) {
            WebAuthenticationDetails details = (WebAuthenticationDetails) a.getDetails();
            remoteIp = details.getRemoteAddress();
    }
    String userName = null;
    String rawPass;
    try {
        db_duration.start();
        userName = a.getPrincipal().toString();
        YourMicroserviceUserDetails userDetails =
                (YourMicroserviceUserDetails) detailsService.loadUserByUsername(userName);
        db_duration.stop();

        pw_duration.start();
        rawPass = a.getCredentials().toString();
        String storedHashedPass = userDetails.getPassword();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(YourMicroserviceSecurityConstants.BCRYPT_STRENGTH_SETTING);

        if (!encoder.matches(rawPass, storedHashedPass)) {
            pw_duration.stop();
            logger.info("{} IP:[{}]", USERNAME_OR_PASSWORD_IS_INVALID_MESSAGE, remoteIp);
            throw new BadCredentialsException(USERNAME_OR_PASSWORD_IS_INVALID_MESSAGE);
        }
        pw_duration.stop();

        if (!userDetails.isEnabled()) {
            if (!userDetails.isAccountNonLocked())
                throw new LockedException(ACCOUNT_IS_LOCKED_MESSAGE) {
                };

            if (!userDetails.isAccountNonExpired())
                throw new AccountExpiredException(ACCOUNT_IS_EXPIRED_MESSAGE) {
                };

            throw new DisabledException(ACCOUNT_IS_DISABLED_MESSAGE) {
            };
        }

        /**
         * Clear all Memory Constructs
         */
        rawPass = null;
        storedHashedPass = null;
        userDetails.shredCredentials();
        /**
         * Return Authentication Token...
         */
        return new YourMSAuthenticationToken(userDetails);

    } catch (UsernameNotFoundException ex) {
        logger.warn("Entity:[" + userName + "] Not Found, Ignoring!");
        throw new BadCredentialsException(USERNAME_OR_PASSWORD_IS_INVALID_MESSAGE);
    } finally {
        /**
         * Report our Authentication Timings
         */
        overall_duration.stop();
        logger.info("Authentication Timings: DB:" + db_duration.getElapsedtoString() +
                ", PW: " + pw_duration + ", Overall: " +
                overall_duration.getElapsedtoString());
    }
}
 
開發者ID:jaschenk,項目名稱:Your-Microservice,代碼行數:74,代碼來源:YourMSAuthenticationManager.java

示例11: getDetails

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
public static DiscordUserDetails getDetails(Authentication authentication) {
    if (authentication != null && authentication.getDetails() instanceof DiscordUserDetails) {
        return (DiscordUserDetails) authentication.getDetails();
    }
    return null;
}
 
開發者ID:GoldRenard,項目名稱:JuniperBotJ,代碼行數:7,代碼來源:SecurityUtils.java

示例12: getCurrentUser

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@Override
public User getCurrentUser() {
    final Authentication authentication = ofNullable(SecurityContextHolder.getContext().getAuthentication())
            .orElseThrow(() -> new AccessDeniedException("There is no authorized user"));
    return ((User) authentication.getDetails());
}
 
開發者ID:akraskovski,項目名稱:product-management-system,代碼行數:7,代碼來源:DefaultUserService.java

示例13: addSocialUser

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
public void addSocialUser(Principal principal) {

        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) principal;

        Authentication authentication = oAuth2Authentication.getUserAuthentication();

        Map<String, String> authenticationDetails = (LinkedHashMap<String, String>) authentication.getDetails();

        User user = new User();

        user.setName(authenticationDetails.get("name"));

        user.setLogin(authenticationDetails.get("id"));

        user.setEnabled(true);

        Role role = roleRepository.findByName("ROLE_ADMIN");
        user.getRoles().add(role);

        userRepository.save(user);
    }
 
開發者ID:arityllc,項目名稱:referenceapp,代碼行數:22,代碼來源:SocialLoginAuthorizationManager.java

示例14: socialUser

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@RequestMapping("/socialUser")
public Map<String, Object> socialUser(Principal principal) {

    OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) principal;

    Authentication authentication = oAuth2Authentication.getUserAuthentication();

    Map<String, String> authenticationDetails = (LinkedHashMap<String, String>) authentication.getDetails();

    UserDetails user = null;

    try {
        user = userDetailsService.loadUserByLogin(authenticationDetails.get("id"));
    } catch (UsernameNotFoundException e) {
    }

    if (user == null) {
        socialLoginAuthorizationManager.addSocialUser(principal);
        user = userDetailsService.loadUserByLogin(authenticationDetails.get("id"));
    }

    Map<String, Object> map = new LinkedHashMap<String, Object>();

    map.put("userAuthentication", authentication.isAuthenticated());

    map.put("name", user.getUsername());

    map.put("roles", authoritiesAsSet(user.getAuthorities()));

    return map;
}
 
開發者ID:arityllc,項目名稱:referenceapp,代碼行數:32,代碼來源:OAuthService.java


注:本文中的org.springframework.security.core.Authentication.getDetails方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。