我想保护我的REST端点,但是遇到麻烦...使用inMemoryAuth
时还不错,但是由于我尝试使用存储在数据库中的凭据-它停止了工作。 / p>
好,所以我的Entity
类看起来像这样
class User {
@Id
@GeneratedValue
@Column(name = "user_id")
private Integer id;
@Column
private String username;
@Column
private String password;
@ManyToMany
@JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles;
}
class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "role_id")
private Integer id;
@Column(name = "role")
private String role;
}
我的安全配置
@Configuration
class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Value("${spring.queries.users-query}")
private String usersQuery;
@Value("${spring.queries.roles-query}")
private String rolesQuery;
private DataSource dataSource;
public SecurityConfiguration(DataSource dataSource) {
this.dataSource = dataSource;
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
return bCryptPasswordEncoder;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication()
.usersByUsernameQuery(usersQuery)
.authoritiesByUsernameQuery(rolesQuery)
.dataSource(dataSource)
.passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic()
.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/task/**").hasRole("USER")
.and()
.csrf().disable()
.formLogin().disable();
}
}
最后,application.properties
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/teamplanner?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Europe/Warsaw
spring.datasource.username=root
spring.datasource.password=root
spring.queries.users-query=select username, password from user where username=?
spring.queries.roles-query=select u.username, r.role from user u inner join user_role ur on(u.user_id=ur.user_id) inner join role r on(ur.role_id=r.role_id) where u.username=?
现在,我正在尝试使用邮递员中的基本身份验证来调用/ task / all,我得到了
{
"timestamp": "2019-04-21T22:50:17.189+0000",
"status": 401,
"error": "Unauthorized",
"message": "Unauthorized",
"path": "/task/all"
}
我存储在application.properties中的两个查询如果直接在数据库中运行它们都会返回记录