当前位置: 首页>>代码示例>>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;未经允许,请勿转载。