优化代码,实体类继承UserDetails

master
barney 2 months ago
parent 786bbf8622
commit c9a4b9c5a1
  1. 2
      src/main/java/cc/bnblogs/springinit/mapper/UserMapper.java
  2. 36
      src/main/java/cc/bnblogs/springinit/pojo/MyUser.java
  3. 14
      src/main/java/cc/bnblogs/springinit/service/CustomUserDetailsService.java

@ -7,6 +7,8 @@ import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserMapper extends BaseMapper<MyUser> {
@Select("SELECT * FROM users WHERE username = #{username}")
MyUser selectByUsername(String username);
}

@ -1,14 +1,46 @@
package cc.bnblogs.springinit.pojo;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.Collections;
@Data
@TableName("users")
public class MyUser {
public class MyUser implements UserDetails {
// 用户表中的字段如下
@TableId
private Long id;
private String username;
private String password;
private Boolean enabled;
// UserDetails接口需要实现的方法
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return Collections.emptyList();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}

@ -7,8 +7,6 @@ import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.security.core.userdetails.User;
import java.util.Collections;
@Service
public class CustomUserDetailsService implements UserDetailsService {
@ -22,16 +20,6 @@ public class CustomUserDetailsService implements UserDetailsService {
if (user == null) {
throw new UsernameNotFoundException("User not found with username: " + username);
}
// 如果不需要处理权限,直接返回用户信息,默认赋予一个角色
return new User(
user.getUsername(),
user.getPassword(),
user.getEnabled(),
true,
true,
true,
Collections.emptyList()
);
return user;
}
}

Loading…
Cancel
Save