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


Java Authentication.getCredentials方法代碼示例

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


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

示例1: authenticate

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    RawAccessJwtToken rawAccessToken = (RawAccessJwtToken) authentication.getCredentials();

    Jws<Claims> jwsClaims = rawAccessToken.parseClaims(jwtSettings.getTokenSigningKey());
    String orgId = jwsClaims.getBody().getSubject();
    String tenantId = jwsClaims.getBody().get("tenant", String.class);
    List<String> scopes = jwsClaims.getBody().get("scopes", List.class);
    List<GrantedAuthority> authorities = scopes.stream()
            .map(authority -> new SimpleGrantedAuthority(authority))
            .collect(Collectors.toList());
    
    UserContext context = UserContext.create(tenantId, orgId, authorities);
    
    return new JwtAuthenticationToken(context, context.getAuthorities());
}
 
開發者ID:Apereo-Learning-Analytics-Initiative,項目名稱:OpenLRW,代碼行數:17,代碼來源:JwtAuthenticationProvider.java

示例2: authenticate

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
    final JwtToken token = (JwtToken) authentication.getCredentials();
    final Claims claims = jwt.validate(token);

    final String userId = claims.getSubject();
    final String email  = claims.get("mail", String.class);

    @SuppressWarnings("unchecked")
    final List<String> scopes = (List<String>) claims.get("scopes", List.class);
    final List<GrantedAuthority> auths = scopes.stream()
        .map(SimpleGrantedAuthority::new)
        .collect(Collectors.toList());

    final JwtUserDetails user = new JwtUserDetails(userId, email, auths);
    return new JwtAuthentication(token, user);
}
 
開發者ID:membaza,項目名稱:users-service,代碼行數:19,代碼來源:JwtAuthenticationProvider.java

示例3: authenticate

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Assert.notNull(authentication, "No authentication data provided");

    String username = (String) authentication.getPrincipal();
    String password = (String) authentication.getCredentials();

    User user = userService.getByUsername(username).orElseThrow(() -> new UsernameNotFoundException("User not found: " + username));
    
    if (!encoder.matches(password, user.getPassword())) {
        throw new BadCredentialsException("Authentication Failed. Username or Password not valid.");
    }

    if (user.getRoles() == null) throw new InsufficientAuthenticationException("User has no roles assigned");
    
    List<GrantedAuthority> authorities = user.getRoles().stream()
            .map(authority -> new SimpleGrantedAuthority(authority.getRole().authority()))
            .collect(Collectors.toList());
    
    UserContext userContext = UserContext.create(user.getUsername(), authorities);
    
    return new UsernamePasswordAuthenticationToken(userContext, null, userContext.getAuthorities());
}
 
開發者ID:mjfcolas,項目名稱:infotaf,代碼行數:24,代碼來源:AjaxAuthenticationProvider.java

示例4: authenticate

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    // 獲取認證的用戶名 & 密碼
    String name = authentication.getName();
    Object pd = authentication.getCredentials();
    if (pd == null) {
        return new UsernamePasswordAuthenticationToken(name, "", new ArrayList<>());
    }
    String password = pd.toString();
    UserLoginEntity userLoginEntity = loginService.loginValidator(name, password);
    // 認證邏輯
    if (userLoginEntity.isFlag()) {
        return getRole(name, password);
    } else {
        logger.info("登錄失敗,原因是:賬號 {}: {}", userLoginEntity.getUsername(), userLoginEntity.getMessage());
        throw new BadCredentialsException(new GsonBuilder().create().toJson(userLoginEntity));
    }
}
 
開發者ID:hzwy23,項目名稱:hauth-java,代碼行數:19,代碼來源:CustomAuthenticationProvider.java

示例5: authenticate

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
	Usuario user = usuarioRepository.findByEmail(auth.getName());
	if (user == null) {
		flashService.setError("Usuario no encontrado");
		throw new BadCredentialsException("User not found");
	}
	
	String password = (String) auth.getCredentials();
	if (!new BCryptPasswordEncoder().matches(password, user.getPasswordHash())) {
		flashService.setError("Contraseña incorrecta");
		throw new BadCredentialsException("Wrong password");
	}
	
	List<GrantedAuthority> roles = new ArrayList<>();
	for (String role : user.getRoles()) {
		roles.add(new SimpleGrantedAuthority(role));
	}
	
	return new UsernamePasswordAuthenticationToken(user.getEmail(), password, roles);
}
 
開發者ID:arubioVK,項目名稱:La-Apostada,代碼行數:22,代碼來源:UserRepositoryAuthenticationProvider.java

示例6: authenticate

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@Override
public Authentication authenticate(Authentication authentication)
    throws AuthenticationException {
  logger.debug(
      "==== Authenticating using BarAuthenticationProvider: " +
          authentication);

  // here goes username/password authentication for Foo
  Response response = userService
      .authenticateBar(String.valueOf(authentication.getPrincipal()),
          String.valueOf(authentication.getCredentials()));

  if (response.isOk()) {
    List<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority("BAR_READ"));
    authorities.add(new SimpleGrantedAuthority("BAR_WRITE"));
    return new BarUsernamePasswordAuthenticationToken(
        authentication.getPrincipal(), authentication.getCredentials(),
        authorities);
  } else {
    throw new BadCredentialsException("Authentication failed.");
  }
}
 
開發者ID:gdong42,項目名稱:spring-auth-example,代碼行數:24,代碼來源:BarAuthenticationProvider.java

示例7: getCurrentUserJWT

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
/**
 * Get the JWT of the current user.
 *
 * @return the JWT of the current user
 */
public static String getCurrentUserJWT() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    if (authentication != null && authentication.getCredentials() instanceof String) {
        return (String) authentication.getCredentials();
    }
    return null;
}
 
開發者ID:deepu105,項目名稱:spring-io,代碼行數:14,代碼來源:SecurityUtils.java

示例8: authenticate

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    String authenticationToken = (String) authentication.getCredentials();
    AuthenticationTokenDetails authenticationTokenDetails = authenticationTokenService.parseToken(authenticationToken);
    UserDetails userDetails = this.userDetailsService.loadUserByUsername(authenticationTokenDetails.getUsername());

    return new JwtAuthenticationToken(userDetails, authenticationTokenDetails, userDetails.getAuthorities());
}
 
開發者ID:cassiomolin,項目名稱:jersey-jwt-springsecurity,代碼行數:10,代碼來源:JwtAuthenticationProvider.java

示例9: extractAuthentication

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@Override
public Authentication extractAuthentication(Map<String, ?> map) {
    Authentication authentication = super.extractAuthentication(map);
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    AuthenticatedUser user = new AuthenticatedUser(getUsername(map), getFistName(map), getLastName(map), authorities);
    return new UsernamePasswordAuthenticationToken(user, authentication.getCredentials(), authorities);
}
 
開發者ID:SopraSteriaGroup,項目名稱:initiatives_backend_auth,代碼行數:8,代碼來源:CustomUserAuthenticationConverter.java

示例10: authenticate

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
    JWTAuthenticationToken authentication = (JWTAuthenticationToken) auth;
    if(authentication.getCredentials() == null || !(authentication.getCredentials() instanceof String)) {
        logger.error("Credentials not present");
        return null;
    }
    String rawToken = (String) auth.getCredentials();
    DecodedJWT token = JWTSecurityService.verify(jwtKey, rawToken);
    Claim path = token.getClaim(JWTSecurityService.CLAIM_PATH);
    authentication.setAuthenticated(true);

    // TODO:AD This is super unfortunate, but not sure there is a better way when using JSP
    if(StringUtils.contains(authentication.getRequestedPath(), "/WEB-INF/jsp/")) {
        logger.warn("BYPASSING AUTH FOR WEB-INF page");
    } else

    if(!roughlyEqual(path.asString(), authentication.getRequestedPath())) {
        throw new InsufficientAuthenticationException("Credentials not valid for path " + authentication
                .getRequestedPath() + ". They are valid for " + path.asString());
    }

    List<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority("IS_AUTHENTICATED_FULLY"));
    authorities.add(new SimpleGrantedAuthority("ROLE_TEMP"));
    return new JWTAuthenticationToken(authorities, rawToken, authentication.getRequestedPath());
}
 
開發者ID:airsonic,項目名稱:airsonic,代碼行數:28,代碼來源:JWTAuthenticationProvider.java

示例11: createSuccessAuthentication

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@Override
protected Authentication createSuccessAuthentication(Object principal, Authentication authentication, UserDetails user) {
	DelegateUsernamePasswordAuthenticationToken result = new DelegateUsernamePasswordAuthenticationToken(principal, authentication.getCredentials(), null);
	result.setDetails(authentication.getDetails());
	result.setAuthoritiesAccessor(this::getAuthorities);
	return result;
}
 
開發者ID:yushijinhun,項目名稱:akir,代碼行數:8,代碼來源:AkirAuthenticationProvider.java

示例12: authenticate

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    RawAccessJwtToken rawAccessToken = (RawAccessJwtToken) authentication.getCredentials();

    Jws<Claims> jwsClaims = rawAccessToken.parseClaims(AppConfig.prop.getProperty("security.tokenSigningKey"));
    String subject = jwsClaims.getBody().getSubject();
    List<String> scopes = jwsClaims.getBody().get("scopes", List.class);
    List<GrantedAuthority> authorities = scopes.stream()
            .map(authority -> new SimpleGrantedAuthority(authority))
            .collect(Collectors.toList());
    
    UserContext context = UserContext.create(subject, authorities);
    
    return new JwtAuthenticationToken(context, context.getAuthorities());
}
 
開發者ID:mjfcolas,項目名稱:infotaf,代碼行數:16,代碼來源:JwtAuthenticationProvider.java

示例13: authenticate

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  RawAccessJwtToken rawAccessToken = (RawAccessJwtToken) authentication.getCredentials();
  SecurityUser securityUser = tokenFactory.parseAccessJwtToken(rawAccessToken);
  return new JwtAuthenticationToken(securityUser);
}
 
開發者ID:osswangxining,項目名稱:iotplatform,代碼行數:7,代碼來源:JwtAuthenticationProvider.java

示例14: authenticate

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
	//1. 파라미터로 전달받은 Authentication 객체의 인증처리가 지원되지 않으면 null이 리턴
	
	if(!supports(auth.getClass())){
		return null;
	}
	
	//2. 인증됬다면, 인수로 받는 user정보를 가지고 디비에 존재하는지 체크(id check)
	
	String userId = auth.getName();
	System.out.println("userId:"+userId);
	Member vo = memberDAO.findMemberById(userId);
	
	if(vo==null){// ID가 없는경우
		throw new UsernameNotFoundException(userId+"는 없는 회원입니다.");//spring exception
	}
	
	//3.id가 존재하면 비밀번호 비교
	String password = (String)auth.getCredentials();//비밀번호
	System.out.println("password:"+password);
	if(!passwordEncoder.matches(password, vo.getPassword())){
		throw new BadCredentialsException("패스워드 오류입니다.");
	}
	
    ////////////    여기까지 왔다면 인증에 성공함  ///////////////// 
	//4. id, password 모두가 일치하면 Authentication를 만들어서 리턴.
	// 사용자의 권한을 조회 : 하나의 사용자는 여러개의 권한을 가짐.
	List<Authority> list = 
			authoritiesDAO.selectAuthorityByUserName(userId);
	System.out.println("list:"+list);
	if(list.isEmpty()){
		//아무 권한이 없는경우....
		throw new UsernameNotFoundException(userId+"는 아무 권한이 없습니다.");
	}
	
	//db에서 가지고 온 권한을 GrantedAuthority 로 변환해야함.
	List<SimpleGrantedAuthority> authList = new ArrayList<SimpleGrantedAuthority>();
	for(Authority authority : list){
		authList.add(new SimpleGrantedAuthority(authority.getRole()));
	}
	//UsernamePasswordAuthenticationToken(Object principal, Object credentials, authorities)
	//UsernamePasswordAuthenticationToken는 Authentication의 자식객체
	//인증완료된 결과로 UsernamePasswordAuthenticationToken를 리턴한다.
	return new UsernamePasswordAuthenticationToken(vo, null, authList);
}
 
開發者ID:INSUPARK83,項目名稱:way_learning,代碼行數:47,代碼來源:MemberAuthenticationProvider.java

示例15: 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


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