public interface UserDetails extends Serializable { /** * Returns the authorities granted to the user. Cannot return <code>null</code>. * @return the authorities, sorted by natural key (never <code>null</code>) */ Collection<? extends GrantedAuthority> getAuthorities(); /** * Returns the password used to authenticate the user. * @return the password */ String getPassword(); /** * Returns the username used to authenticate the user. Cannot return * <code>null</code>. * @return the username (never <code>null</code>) */ String getUsername(); /** * Indicates whether the user's account has expired. An expired account cannot be * authenticated. * @return <code>true</code> if the user's account is valid (ie non-expired), * <code>false</code> if no longer valid (ie expired) */ boolean isAccountNonExpired(); /** * Indicates whether the user is locked or unlocked. A locked user cannot be * authenticated. * @return <code>true</code> if the user is not locked, <code>false</code> otherwise */ boolean isAccountNonLocked(); /** * Indicates whether the user's credentials (password) has expired. Expired * credentials prevent authentication. * @return <code>true</code> if the user's credentials are valid (ie non-expired), * <code>false</code> if no longer valid (ie expired) */ boolean isCredentialsNonExpired(); /** * Indicates whether the user is enabled or disabled. A disabled user cannot be * authenticated. * @return <code>true</code> if the user is enabled, <code>false</code> otherwise */ boolean isEnabled(); }
时间: 2023-06-25 15:04:09 浏览: 55
这是一个 Java 接口,名为 UserDetails,用于表示用户的详细信息。它包含了以下方法:
1. getAuthorities() 返回授予用户的权限集合。
2. getPassword() 返回用户用于身份验证的密码。
3. getUsername() 返回用户用于身份验证的用户名。
4. isAccountNonExpired() 指示用户的帐户是否已过期。
5. isAccountNonLocked() 指示用户是否已被锁定。
6. isCredentialsNonExpired() 指示用户的凭据(密码)是否已过期。
7. isEnabled() 指示用户是否已启用。
相关问题
项目导入了<groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId>依赖,为什么没有JwtTokenUtil类?
`spring-boot-starter-security`依赖提供了Spring Security的基础集成,但是并没有提供`JwtTokenUtil`类。如果您想要使用`JwtTokenUtil`,您需要手动添加相关的依赖库或者自行定义该类。以下是一个示例`JwtTokenUtil`类的实现:
```java
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
@Component
public class JwtTokenUtil {
private final Key key;
public JwtTokenUtil(@Value("${jwt.secret}") String secret) {
this.key = Keys.hmacShaKeyFor(secret.getBytes());
}
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
return createToken(claims, userDetails.getUsername());
}
public String extractUsername(String token) {
return extractClaim(token, Claims::getSubject);
}
public Date extractExpiration(String token) {
return extractClaim(token, Claims::getExpiration);
}
public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
final Claims claims = extractAllClaims(token);
return claimsResolver.apply(claims);
}
private Claims extractAllClaims(String token) {
return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody();
}
private String createToken(Map<String, Object> claims, String subject) {
final Date now = new Date();
final Date validity = new Date(now.getTime() + 1000 * 60 * 60); // 1 hour validity
return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(now)
.setExpiration(validity).signWith(key, SignatureAlgorithm.HS256).compact();
}
public boolean validateToken(String token, UserDetails userDetails) {
final String username = extractUsername(token);
return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
}
private boolean isTokenExpired(String token) {
final Date expiration = extractExpiration(token);
return expiration.before(new Date());
}
}
```
这个示例类使用了`io.jsonwebtoken`类库来生成和解析JWT令牌。如果您想要使用该类,您需要在`pom.xml`文件中添加以下依赖:
```
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
```
同时,您需要在`application.properties`或`application.yaml`文件中定义JWT的密钥:
```properties
jwt.secret=your-secret-key
```
请注意,这只是一个示例实现,您可以按照您的需求对其进行修改。
为这段代码添加注释@Component public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private PasswordEncoder passwordEncoder; @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { /** * 从数据库查:User是我自己写的类,getOne()是mybatis_plus的中的方法 * 就通过用户名查出一个用户 */ // 这个要从数据库取出来 User usersByUsername = userRepository.findUsersByUsername(username); if (null == usersByUsername) { throw new UsernameNotFoundException(CodeMsg.ADMIN_USERNAME_NO_EXIST.getMsg()); } /** * 创建一个权限集合,随你放多少 * 最后返回一个org.springframework.security.core.userdetails包下的User * 授权就给完了 * 我这里授权的是USER; */ ArrayList<SimpleGrantedAuthority> arrayList = new ArrayList<>(); arrayList.add(new SimpleGrantedAuthority("ROLE_USER")); return new org.springframework.security.core.userdetails.User(usersByUsername.getUsername(),usersByUsername.getPassword(),arrayList); } }
/**
* 这是一个实现了UserDetailsService接口的类,用于加载用户信息
*/
@Component
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private PasswordEncoder passwordEncoder; // 密码加密器
@Autowired
private UserRepository userRepository; // 用户信息仓库
/**
* 通过用户名查找用户信息
* @param username 用户名
* @return 返回一个UserDetails类型的对象
* @throws UsernameNotFoundException 如果用户名不存在则抛出该异常
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 从数据库中查找指定用户名的用户信息
User usersByUsername = userRepository.findUsersByUsername(username);
if (null == usersByUsername) {
// 如果未查询到该用户,则抛出异常
throw new UsernameNotFoundException(CodeMsg.ADMIN_USERNAME_NO_EXIST.getMsg());
}
// 创建一个权限集合,这里只授权了USER
ArrayList<SimpleGrantedAuthority> arrayList = new ArrayList<>();
arrayList.add(new SimpleGrantedAuthority("ROLE_USER"));
// 返回一个org.springframework.security.core.userdetails包下的User对象,其中包含用户信息和授权信息
return new org.springframework.security.core.userdetails.User(
usersByUsername.getUsername(),
usersByUsername.getPassword(),
arrayList
);
}
}