gpt4 book ai didi

In Spring Security, after entering correct username and password, it redirects to the home page but it still displays "HTTP 403 Forbidden"(在Spring Security中,在输入正确的用户名和密码后,它会重定向到主页,但仍然显示“HTTP403禁止”)

转载 作者:bug小助手 更新时间:2023-10-25 16:40:04 32 4
gpt4 key购买 nike



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。非常感谢!


更多回答
优秀答案推荐

There is no stored session to keep you logged in once you are redirected. That's what SessionCreationPolicy.STATELESS means: don't create a server-side session, treat every request individually. You have to authenticate somehow when the browser redirects to /api/home. There are many options but it boils down to one of the following:

重定向后,没有存储的会话可让您保持登录状态。这就是SessionCreationPolicy.STATELESS的意思:不要创建服务器端会话,单独处理每个请求。当浏览器重定向到/api/home时,您必须以某种方式进行身份验证。有很多选择,但归根结底是以下之一:



  • Enable backend sessions, this will tell Spring to link your requests together via the JSESSIONID cookie. This is the simple answer but will lead to problems down the road if you are building an API (see: REST)

  • Include authentication token with each request. For example, make an endpoint that accepts a username and password and returns a token (see: JWT) to the client (browser). The client would then provide that token as a header on subsequent requests to authenticate.


更多回答

should be noted that if selecting JWTs you can not logout the user and that your application will be susceptible to token stealing attacks through cross site scripting etc.

应该注意的是,如果选择JWTs,您将无法注销用户,并且您的应用程序将容易受到跨站点脚本等令牌窃取攻击。

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