So I was practicing my SpringBoot+SpringSecurity skill.
In the security configuration:
所以我在练习我的SpringBoot+SpringSecurity技能。在安全配置中:
@Bean
public SecurityFilterChain configuration(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable);
http.authorizeHttpRequests(Registry -> Registry
.requestMatchers(Constants.PUBLIC_URL)// /auth/**
.permitAll()
.requestMatchers(Constants.AUTHENTICATE_URL)// /api/**
.hasAnyRole(Role.ADMIN.name(), Role.USER.name())
);
http.sessionManagement(session
-> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
http.authenticationProvider(authenticationProvider());
return http.build();
}
This is my authenticate controller:
这是我的身份验证控制器:
@PostMapping("/authenticate")
public String processAuthenticate(@Valid @ModelAttribute(name = "user") AuthenticateRequest authenticateRequest, BindingResult bindingResult) {
bindingResult = authServices.authenticate(authenticateRequest, bindingResult);
if (bindingResult.hasErrors()) {
return "authenticate";
}
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken(
authenticateRequest.getUsername(),
authenticateRequest.getPassword()
)
);
return "redirect:/api/home";
}
So, that's exactly what I think:
if authServices.authenticate(authenticateRequest, bindingResult);
does not throw any exception, which means the correct username and password are entered!
Next, the SecurityContextHolder will set the Authentication(UsernamePasswordAuthentication) and fill it with username and password.
Finally, send redirect to the url "/api/home".
所以,这正是我的想法:如果authServices.authenticate(authenticateRequest,bindingResult);没有抛出任何异常,这意味着输入了正确的用户名和密码!接下来,SecurityContextHolder将设置身份验证(UsernamePasswordAuthentication)并使用用户名和密码填充它。最后,发送重定向到URL“/api/home”。
There are two roles defined: USER and ADMIN.
定义了两个角色:用户和管理员。
public enum Role {
USER(Collections.emptySet()),
ADMIN(Set.of(ADMIN_READ,
ADMIN_UPDATE, ADMIN_CREATE, ADMIN_DELETE
));
@Getter
private final Set<Permission> permissions;
public List<SimpleGrantedAuthority> getAuthorities() {
List<SimpleGrantedAuthority> authorities = new java.util.ArrayList<>(getPermissions().stream()
.map(permission -> new SimpleGrantedAuthority(permission.getPermission()))
.toList());
authorities.add(new SimpleGrantedAuthority("ROLE_" + this.name()));
return authorities;
}
}
I think it shall be something wrong in the authorities or roles or something. Because when I delete the .hasAnyRole(Role.ADMIN.name(), Role.USER.name())
and change it to permitAll()
我认为这应该是当局或角色或其他方面的问题。因为当我删除.hasAnyRole(Role.ADMIN.name(),Role.USER.name())并将其更改为permitAll()时
Additionally, there is no AccessDeniedException threw out, only Http 403 Error on the web page.
此外,没有抛出AccessDeniedException,只有网页上的http 403错误。
This is my Mysql table:
'1', 'user1', '$2a$10$faQJhWWffJlvWbN4YDC4tep4TIMDzH3Hze4tH9MMmt6r9NKp49FCe', '[email protected]', 'ADMIN'
这是我的MySql表:‘1’,‘USER1’,‘$2a$10$faQJhWWffJlvWbN4YDC4tep4TIMDzH3Hze4tH9MMmt6r9NKp49FCe’,‘[电子邮件受保护]’,‘ADMIN’
'5', 'user2', '$2a$10$qAZAuvoG.aaEMljYfQirZOhjEUsUZ3edcum/Mhc6UPOc.ti0VD7JO', '[email protected]', 'USER'
‘5’,‘User2’,‘$2a$10$qAZAuvoG.aaEMljYfQirZOhjEUsUZ3edcum/Mhc6UPOc.ti0VD7JO’,‘[受保护的电子邮件]’,‘User’
I've tried:
我试过了:
adding @PreAuthorize("isAuthenticated()")on the homePage controller function but does not help.
and @Secured("ROLE_USER") does not help either.
changing the column "USER" to "ROLE_USER" in the Mysql table does not help.
And, I changed the .hasAnyRole(Role.ADMIN.name(), Role.USER.name())
to .hasAuthority("ADMIN")
,to
.hasAuthority("USER")
,unluckily, they does NOT help.
在主页控制器函数上添加@preAuthorize(“isAuthenticated()”),但无济于事。@Secure(“Role_User”)也无济于事。将MySQL表中的“USER”列更改为“ROLE_USER”无济于事。并且,我将.hasAnyRole(Role.ADMIN.name(),Role.USER.name())更改为.hasAuthority(“admin”),再更改为.hasAuthority(“user”),不幸的是,它们无济于事。
What I expected:
Just tell me the reason for this annoying problem. I wish I can redirect to the /api/home successfully. Thank you very much!
我所期待的:告诉我这个令人讨厌的问题的原因。我希望我能成功重定向到/api/home。非常感谢!
更多回答
我是一名优秀的程序员,十分优秀!