Java Code Examples for org.springframework.security.core.Authentication#getDetails()

The following examples show how to use org.springframework.security.core.Authentication#getDetails() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SpringEventListener.java    From ranger with Apache License 2.0 6 votes vote down vote up
protected void process(AuthenticationFailureDisabledEvent authFailEvent) {
Authentication auth = authFailEvent.getAuthentication();
WebAuthenticationDetails details = (WebAuthenticationDetails) auth
	.getDetails();
String remoteAddress = details != null ? details.getRemoteAddress()
	: "";
String sessionId = details != null ? details.getSessionId() : "";

logger.info("Login Unsuccessful:" + auth.getName() + " | Ip Address:"
	+ remoteAddress);

sessionMgr.processFailureLogin(XXAuthSession.AUTH_STATUS_DISABLED,
	XXAuthSession.AUTH_TYPE_PASSWORD, auth.getName(),
	remoteAddress, sessionId);

   }
 
Example 2
Source File: ChoerodonAuthenticationKeyGenerator.java    From oauth-server with Apache License 2.0 6 votes vote down vote up
@Override
public String extractKey(OAuth2Authentication authentication) {
    Map<String, String> values = new LinkedHashMap<>();
    OAuth2Request authorizationRequest = authentication.getOAuth2Request();
    if (!authentication.isClientOnly()) {
        values.put(USERNAME, authentication.getName());
    }
    values.put(CLIENT_ID, authorizationRequest.getClientId());
    if (authorizationRequest.getScope() != null) {
        values.put(SCOPE, OAuth2Utils.formatParameterList(new TreeSet<>(authorizationRequest.getScope())));
    }
    Authentication auth = authentication.getUserAuthentication();
    if (auth != null && auth.getDetails() instanceof WebAuthenticationDetails) {
        String sessionId = ((WebAuthenticationDetails) auth.getDetails()).getSessionId();
        logger.info("sessionId : {}", sessionId);
        if (!StringUtils.isEmpty(sessionId)) {
            values.put(SESSION, sessionId);
        }
    }
    return generateKey(values);
}
 
Example 3
Source File: CustomAuthenticationProvider.java    From microservice-integration with MIT License 6 votes vote down vote up
@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);
}
 
Example 4
Source File: OrderController.java    From spring-cloud-study with Apache License 2.0 6 votes vote down vote up
@GetMapping(value = "get")
//@PreAuthorize("hasAuthority('ROLE_ADMIN')")
@PreAuthorize("hasAnyRole('ROLE_ADMIN')")
public Object get(Authentication authentication){
    //Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    authentication.getCredentials();
    OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)authentication.getDetails();
    String jwtToken = details.getTokenValue();
    Claims claims = Jwts.parser()
            .setSigningKey("dev".getBytes(StandardCharsets.UTF_8))
            .parseClaimsJws(jwtToken)
            .getBody();
    return claims;
    //return "给你";
}
 
Example 5
Source File: CustomAuthenticationProvider.java    From blog-sample with Apache License 2.0 6 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    // 获取用户输入的用户名和密码
    String inputName = authentication.getName();
    String inputPassword = authentication.getCredentials().toString();

    CustomWebAuthenticationDetails details = (CustomWebAuthenticationDetails) authentication.getDetails();

    String verifyCode = details.getVerifyCode();
    if (!validateVerify(verifyCode)) {
        throw new DisabledException("验证码输入错误");
    }

    // userDetails为数据库中查询到的用户信息
    UserDetails userDetails = customUserDetailsService.loadUserByUsername(inputName);

    // 这里直接偷懒手动密码校验了,也可以通过注入 passwordEncode 实现
    if (!userDetails.getPassword().equals(inputPassword)) {
        throw new BadCredentialsException("密码错误");
    }

    return new UsernamePasswordAuthenticationToken(inputName, inputPassword, userDetails.getAuthorities());
}
 
Example 6
Source File: UserFeignClientInterceptor.java    From cubeai with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(RequestTemplate template) {

    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();

    if (authentication != null && authentication.getDetails() instanceof OAuth2AuthenticationDetails) {

        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
        template.header(AUTHORIZATION_HEADER, String.format("%s %s", BEARER_TOKEN_TYPE, details.getTokenValue()));
    }
}
 
Example 7
Source File: CustomAuthenticationProvider.java    From zhcet-web with Apache License 2.0 5 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String userId = (String) authentication.getPrincipal();
    CustomAuthenticationDetails details = (CustomAuthenticationDetails) authentication.getDetails();

    boolean isBlocked = loginAttemptService.isBlocked(userId);

    if (isBlocked) {
        log.debug("User account is locked");

        throw new LockedException(messages.getMessage(
                "AbstractUserDetailsAuthenticationProvider.locked",
                "User account is locked"));
    }

    Authentication authenticated = super.authenticate(authentication);

    UserAuth userAuth = (UserAuth) authenticated.getPrincipal();

    if (!userAuth.isUsing2fa())
        return authenticated;

    String code = details.getTotpCode();
    String secret = userAuth.getTotpSecret();
    if (secret == null || code == null) {
        throw new BadCredentialsException("OTP was not provided");
    } else if (TwoFAService.isInvalidOtp(secret, code)) {
        throw new BadCredentialsException("OTP was incorrect. Please try again");
    }

    return authenticated;
}
 
Example 8
Source File: Message.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
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;
}
 
Example 9
Source File: SpringSecurityListener.java    From lemon with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 10
Source File: CodeClientController.java    From spring-cloud-study with Apache License 2.0 5 votes vote down vote up
@org.springframework.web.bind.annotation.ResponseBody
@GetMapping(value = "get")
@PreAuthorize("hasAnyRole('ROLE_ADMIN')")
public Object get(Authentication authentication) {
    //Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    authentication.getCredentials();
    OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
    String token = details.getTokenValue();
    return token;
}
 
Example 11
Source File: UserController.java    From spring-cloud-study with Apache License 2.0 5 votes vote down vote up
@GetMapping(value = "jwt")
@PreAuthorize("hasAnyRole('ROLE_ADMIN')")
public Object jwtParser(Authentication authentication){
    authentication.getCredentials();
    OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)authentication.getDetails();
    String jwtToken = details.getTokenValue();
    Claims claims = Jwts.parser()
            .setSigningKey("dev".getBytes(StandardCharsets.UTF_8))
            .parseClaimsJws(jwtToken)
            .getBody();
    return claims;
}
 
Example 12
Source File: UserFeignClientInterceptor.java    From cubeai with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(RequestTemplate template) {

    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();

    if (authentication != null && authentication.getDetails() instanceof OAuth2AuthenticationDetails) {

        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
        template.header(AUTHORIZATION_HEADER, String.format("%s %s", BEARER_TOKEN_TYPE, details.getTokenValue()));
    }
}
 
Example 13
Source File: KeycloakAuthenticationProvider.java    From camunda-bpm-identity-keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public AuthenticationResult extractAuthenticatedUser(HttpServletRequest request, ProcessEngine engine) {

	// Extract authentication details
    OAuth2Authentication authentication = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null) {
        return AuthenticationResult.unsuccessful();
    }
    Authentication userAuthentication = authentication.getUserAuthentication();
    if (userAuthentication == null || userAuthentication.getDetails() == null) {
        return AuthenticationResult.unsuccessful();
    }
    
    // Extract user ID from Keycloak authentication result - which is part of the requested user info
    @SuppressWarnings("unchecked")
    // String userId = ((HashMap<String, String>) userAuthentication.getDetails()).get("sub");
    String userId = ((HashMap<String, String>) userAuthentication.getDetails()).get("email"); // useEmailAsCamundaUserId = true
    // String userId = ((HashMap<String, String>) userAuthentication.getDetails()).get("preferred_username"); // useUsernameAsCamundaUserId = true
    if (StringUtils.isEmpty(userId)) {
        return AuthenticationResult.unsuccessful();
    }

    // Authentication successful
    AuthenticationResult authenticationResult = new AuthenticationResult(userId, true);
    authenticationResult.setGroups(getUserGroups(userId, engine));

    return authenticationResult;
}
 
Example 14
Source File: AuthContextUtils.java    From syncope with Apache License 2.0 5 votes vote down vote up
public static String getDomain() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    String domainKey = auth != null && auth.getDetails() instanceof SyncopeAuthenticationDetails
            ? SyncopeAuthenticationDetails.class.cast(auth.getDetails()).getDomain()
            : null;
    if (StringUtils.isBlank(domainKey)) {
        domainKey = SyncopeConstants.MASTER_DOMAIN;
    }

    return domainKey;
}
 
Example 15
Source File: AccountLogListener.java    From lemon with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 16
Source File: AuthenticationServiceImpl.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
@Override
public User onAuthenticationSuccess(Authentication auth) {
    final DefaultUser principal = (DefaultUser) auth.getPrincipal();

    final EndUserAuthentication authentication = new EndUserAuthentication(principal.getUsername(), null, new SimpleAuthenticationContext());
    Map<String, String> details = auth.getDetails() == null ? new HashMap<>() : new HashMap<>((Map) auth.getDetails());
    details.forEach(authentication.getContext()::set);
    authentication.getContext().set(Claims.organization, Organization.DEFAULT);

    final String source = details.get(SOURCE);
    io.gravitee.am.model.User endUser = userService.findByExternalIdAndSource(ReferenceType.ORGANIZATION, Organization.DEFAULT, principal.getId(), source)
            .switchIfEmpty(Maybe.defer(() -> userService.findByUsernameAndSource(ReferenceType.ORGANIZATION, Organization.DEFAULT, principal.getUsername(), source)))
            .switchIfEmpty(Maybe.error(new UserNotFoundException(principal.getUsername())))
            .flatMapSingle(existingUser -> {
                existingUser.setSource(details.get(SOURCE));
                existingUser.setClient(CLIENT_ID);
                existingUser.setLoggedAt(new Date());
                existingUser.setLoginsCount(existingUser.getLoginsCount() + 1);
                // set roles
                if (existingUser.getRoles() == null) {
                    existingUser.setRoles(principal.getRoles());
                } else if (principal.getRoles() != null) {
                    // filter roles
                    principal.getRoles().removeAll(existingUser.getRoles());
                    existingUser.getRoles().addAll(principal.getRoles());
                }
                existingUser.setAdditionalInformation(principal.getAdditionalInformation());
                return userService.update(existingUser);
            })
            .onErrorResumeNext(ex -> {
                if (ex instanceof UserNotFoundException) {
                    final io.gravitee.am.model.User newUser = new io.gravitee.am.model.User();
                    newUser.setInternal(false);
                    newUser.setUsername(principal.getUsername());
                    newUser.setSource(details.get(SOURCE));
                    newUser.setClient(CLIENT_ID);
                    newUser.setReferenceType(ReferenceType.ORGANIZATION);
                    newUser.setReferenceId(Organization.DEFAULT);
                    newUser.setLoggedAt(new Date());
                    newUser.setLoginsCount(1l);
                    newUser.setAdditionalInformation(principal.getAdditionalInformation());
                    return userService.create(newUser)
                            .flatMap(user -> setRoles(principal, user)
                                    .map(membership -> user));
                }
                return Single.error(ex);
            })
            .flatMap(userService::enhance)
            .doOnSuccess(user -> auditService.report(AuditBuilder.builder(AuthenticationAuditBuilder.class).principal(authentication).referenceType(ReferenceType.ORGANIZATION).referenceId(Organization.DEFAULT).client(CLIENT_ID).user(user)))
            .blockingGet();

    principal.setId(endUser.getId());
    principal.getAdditionalInformation().put(StandardClaims.SUB, endUser.getId());
    principal.getAdditionalInformation().put(Claims.organization, endUser.getReferenceId());
    principal.getAdditionalInformation().put("login_count", endUser.getLoginsCount());

    // set roles
    Set<String> roles = endUser.getRoles() != null ? new HashSet<>(endUser.getRoles()) : new HashSet<>();
    if (principal.getRoles() != null) {
        roles.addAll(principal.getRoles());
    }

    principal.getAdditionalInformation().put(CustomClaims.ROLES, roles);

    return principal;
}
 
Example 17
Source File: SecurityUtils.java    From JuniperBot with GNU General Public License v3.0 4 votes vote down vote up
public static DiscordUserDetails getDetails(Authentication authentication) {
    if (authentication != null && authentication.getDetails() instanceof DiscordUserDetails) {
        return (DiscordUserDetails) authentication.getDetails();
    }
    return null;
}
 
Example 18
Source File: TokenAuthenticationHelper.java    From SpringSecurity-JWT-Vue-Deom with MIT License 4 votes vote down vote up
/**
 * 设置登陆成功后令牌返回
 * */
public static void addAuthentication(HttpServletRequest request,  HttpServletResponse response, Authentication authResult) throws IOException {
    // 获取用户登陆角色
    Collection<? extends GrantedAuthority> authorities = authResult.getAuthorities();
    // 遍历用户角色
    StringBuffer stringBuffer = new StringBuffer();
    authorities.forEach(authority -> {
        stringBuffer.append(authority.getAuthority()).append(",");
    });
    long expirationTime = EXPIRATION_TIME;
    int cookExpirationTime = -1;
    // 处理登陆附加信息
    LoginDetails loginDetails = (LoginDetails) authResult.getDetails();
    if (loginDetails.getRememberMe() != null && loginDetails.getRememberMe()) {
        expirationTime = COOKIE_EXPIRATION_TIME * 1000;
        cookExpirationTime = COOKIE_EXPIRATION_TIME;
    }

    String jwt = Jwts.builder()
            // Subject 设置用户名
            .setSubject(authResult.getName())
            // 设置用户权限
            .claim("authorities", stringBuffer)
            // 过期时间
            .setExpiration(new Date(System.currentTimeMillis() + expirationTime))
            // 签名算法
            .signWith(SignatureAlgorithm.HS512, SECRET_KEY)
            .compact();
    Cookie cookie = new Cookie(COOKIE_TOKEN, jwt);
    cookie.setHttpOnly(true);
    cookie.setPath("/");
    cookie.setMaxAge(cookExpirationTime);
    response.addCookie(cookie);

    // 向前端写入数据
    LoginResultDetails loginResultDetails = new LoginResultDetails();
    ResultDetails resultDetails = new ResultDetails();
    resultDetails.setStatus(HttpStatus.OK.value());
    resultDetails.setMessage("登陆成功!");
    resultDetails.setSuccess(true);
    resultDetails.setTimestamp(LocalDateTime.now());
    User user = new User();
    user.setUsername(authResult.getName());
    user.setPower(stringBuffer.toString());
    user.setExpirationTime(System.currentTimeMillis() + expirationTime);

    loginResultDetails.setResultDetails(resultDetails);
    loginResultDetails.setUser(user);
    loginResultDetails.setStatus(200);
    response.setContentType("application/json; charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.write(new ObjectMapper().writeValueAsString(loginResultDetails));
    out.flush();
    out.close();
}
 
Example 19
Source File: DefaultAuthenticationProvider.java    From DataHubSystem with GNU Affero General Public License v3.0 4 votes vote down vote up
@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";
   if (authentication.getDetails () instanceof WebAuthenticationDetails)
   {
      ip = ((WebAuthenticationDetails)authentication.getDetails ())
            .getRemoteAddress ();
   }
   LOGGER.info ("Connection attempted by '" + authentication.getName () +
         "' from " + 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 ());
}
 
Example 20
Source File: KylinAuthenticationProvider.java    From kylin-on-parquet-v2 with Apache License 2.0 4 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    byte[] hashKey = hf.hashString(authentication.getName() + authentication.getCredentials()).asBytes();
    String userKey = Arrays.toString(hashKey);

    if (userService.isEvictCacheFlag()) {
        userCache.invalidateAll();
        userService.setEvictCacheFlag(false);
    }
    Authentication authed = userCache.getIfPresent(userKey);

    if (null != authed) {
        SecurityContextHolder.getContext().setAuthentication(authed);
    } else {
        try {
            authed = authenticationProvider.authenticate(authentication);

            ManagedUser user;

            if (authed.getDetails() == null) {
                //authed.setAuthenticated(false);
                throw new UsernameNotFoundException(
                        "User not found in LDAP, check whether he/she has been added to the groups.");
            }

            if (authed.getDetails() instanceof UserDetails) {
                UserDetails details = (UserDetails) authed.getDetails();
                user = new ManagedUser(details.getUsername(), details.getPassword(), false,
                        details.getAuthorities());
            } else {
                user = new ManagedUser(authentication.getName(), "skippped-ldap", false, authed.getAuthorities());
            }
            Assert.notNull(user, "The UserDetail is null.");

            String username = user.getUsername();
            logger.debug("User {} authorities : {}", username, user.getAuthorities());
            if (!userService.userExists(username)) {
                userService.createUser(user);
            } else if (needUpdateUser(user, username)) {
                userService.updateUser(user);
            }

            userCache.put(userKey, authed);
        } catch (AuthenticationException e) {
            logger.error("Failed to auth user: " + authentication.getName(), e);
            throw e;
        }

        logger.debug("Authenticated user " + authed.toString());
    }

    return authed;
}