我,我试图doDoList Rest API并且遇到一些问题。 救救我!
我决定做多用户项目,使用Spring Security的基本身份验证来分离用户。这是我的实体:Task.java
@Entity
public class Task {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
private String title;
@JsonFormat(pattern = "yyyy-MM-dd")
private LocalDate date;
private boolean status;
@ManyToOne
private User user;
public Task() {};
+Getters and Setters
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
private String username;
@JsonIgnore
private String password;
@JsonIgnore
private String[] roles;
public User() {};
+Getters and Setter;
两个实体接口都扩展了CrudRepository。任务与用户有@ManyToOne关系。 Java帮助我根据application.properties
中的设置在h2中创建bd# H2
spring.h2.console.enabled=true
spring.h2.console.path=/h2
# Datasource
spring.datasource.url=jdbc:h2:./data/ToDoList
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.show-sql = true
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
问题#1:我无法打开h2控制台。所有的crud操作都运行良好,我测试它Postman,但我想访问控制台。
然后我实现UserDetailService来获取用户属性:
@Component
public class DetailsService implements UserDetailsService{
@Autowired
private UserRepository users;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = users.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException(username + " was not found");
}
return new org.springframework.security.core.userdetails.User(
user.getUsername(),
user.getPassword(),
AuthorityUtils.createAuthorityList(user.getRoles())
);
}
}
并配置WebSecurity:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private DetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic()
.and()
.csrf().disable();
}
}
这是问题#2 :如何获取有关一个用户的任务的信息? 例如,在findAll方法中。
P.S。对不起我的法语(c)。
UPD。 尝试从SecurityContext中分析用户的数据。创建新文件UserController。这样做很好。访问H2控制台仍有问题...
@RestController
@RequestMapping("/api/v1")
public class UserController {
@Autowired
private TaskRepository tasks;
@GetMapping("/tasks")
public List<Task> getAllTasks() {
List<Task> allTasks = tasks.findAll();
List<Task> userTasks = new ArrayList<>();
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String username = ((UserDetails)principal).getUsername();
for (Task t: allTasks) {
if (t.getUser().getUsername().equals(username)) {
userTasks.add(t);
}
}
return userTasks;
}
}