本文整理汇总了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());
}
示例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);
}
示例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());
}
示例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));
}
}
示例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);
}
示例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.");
}
}
示例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;
}
示例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());
}
示例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());
}
示例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;
}
示例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());
}
示例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);
}
示例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);
}
示例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 ());
}