gpt4 book ai didi

java - 配置spring security后出现未授权调用

转载 作者:行者123 更新时间:2023-11-29 16:05:25 24 4
gpt4 key购买 nike

我想保护我的 REST 端点,但我遇到了麻烦...当我使用 inMemoryAuth 时一切都很好,但由于我尝试使用存储在数据库中的凭据 - 它停止了工作。

好的,所以我的 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=?

现在,我尝试在 postman 中使用基本身份验证来调用/task/all ,我得到了

{
"timestamp": "2019-04-21T22:50:17.189+0000",
"status": 401,
"error": "Unauthorized",
"message": "Unauthorized",
"path": "/task/all"
}

如果我直接在数据库中运行,我存储在 application.properties 中的两个查询都会返回记录

最佳答案

你应该告诉spring security该用户已启用,请参阅JdbcDaoImpl中的源代码

enter image description here

所以你应该更改配置spring.queries.users-query

spring.queries.users-query=select username, password, 1 from user where username=?

如果您仍然无法理解,请将角色名称的值从 USER 更改为 ROLE_USER

关于java - 配置spring security后出现未授权调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55787476/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com