在Spring Security中,登录页面一直在重新加载经过验证的页面



我正在为我的spring启动web项目添加spring安全性。这是可以的,当去允许页面,重新注册页面。但是在需要的认证页面中,提交后登录页面一直在重新加载。

我怀疑在进行身份验证时出了问题。我读了日志文件,但没有帮助。failureUrl("/login?error=true")无异常

我的代码有什么问题?

在这里

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>  
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity6</artifactId>
</dependency>

这是安全配置文件

@Configuration
@EnableWebSecurity
public class WebSecurity {
@Autowired
UserDetailsService userDetailsService;

@Autowired 
BCryptPasswordEncoder passwordEncoder;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder);
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeHttpRequests((authorize) ->
authorize.requestMatchers("/register/**").permitAll()
.requestMatchers("/index").permitAll()
.requestMatchers("/brand","/shop").hasRole("ADMIN")
).formLogin(
form -> form
.loginPage("/login")
// .loginProcessingUrl("/login")
.defaultSuccessUrl("/index")
.failureUrl("/login?error=true")
.permitAll()
).logout(
logout -> logout
.logoutRequestMatcher(new AntPathRequestMatcher("/checkout"))
.permitAll()
);
return http.build();
}

@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().requestMatchers("/image/**", "/js/**","/css/**");
}

用户类

public class Users {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int user_id;
private String user_name ="anonymous";
private String password;
private Long phone = 12345L;
private String gender = "male";
private String email;
public String main_image = "1.jpeg";
private Date created_date;
private String main_address;
private boolean enabled;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(
name = "users_roles",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id")
)
private List<Role> roles = new ArrayList<>();}

角色类

@Entity
@Table(name = "role")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int role_id;
private String name;
@ManyToMany(mappedBy="roles")
private List<Users> users;

}

这里是UserDetailServiceImpl

public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UsersRepository UsersRepository;
@Override
public UserDetails loadUserByUsername(String username) 
throws UsernameNotFoundException {
Users user = UsersRepository.getUserByUsername(username);

if (user == null) {
throw new UsernameNotFoundException("Could not find user");
}
else{
return new org.springframework.security.core.userdetails.User(user.getUser_name(),
user.getPassword(),
mapRolesToAuthorities(user.getRoles()));
}       
}
private Collection < ? extends GrantedAuthority> mapRolesToAuthorities(Collection <Role> roles) {
Collection < ? extends GrantedAuthority> mapRoles = roles.stream()
.map(role -> new SimpleGrantedAuthority(role.getName()))
.collect(Collectors.toList());
return mapRoles;
}}

日志文件

Securing POST /shop2023-03-31T19:38:50.289+07:00 DEBUG 12560 --- [nio-8080-exec-5]o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymousSecurityContext
2023-03-31T19:38:50.294+07:00 DEBUG 12560 --- [nio-8080-exec-5] o.s.s.w.s.HttpSessionRequestCache        : Saved request http://localhost:8080/shop?continue to session2023-03-31T19:38:50.298+07:00 DEBUG 12560 --- [nio-8080-exec-5] o.s.s.web.DefaultRedirectStrategy : Redirecting tohttp://localhost:8080/login 
2023-03-31T19:38:50.459+07:00 DEBUG 12560 --- [nio-8080-exec-6] o.s.security.web.FilterChainProxy        : Securing GET /login
2023-03-31T19:38:50.608+07:00 DEBUG 12560 --- [nio-8080-exec-6] o.s.security.web.FilterChainProxy        : Secured GET /login
2023-03-31T19:38:51.094+07:00 DEBUG 12560 --- [nio-8080-exec-6] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext

首先,删除Login post映射方法,因为spring安全性会处理这个问题,我们不需要这样做。

其次,将action=loginth:post添加到thymelef登录页面:

<form action="login" th:method="post">

第三,添加name=usernamename=password作为输入:

<input id="username" type="text" placeholder="Username" name="username">
<input id="password" type="password" placeholder="Password" name="password"> 

下面是为我工作的SecurityFilterChain:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeHttpRequests((authorize) ->
authorize.requestMatchers("/index","/error").permitAll()
.requestMatchers("/shop").hasAnyAuthority("ADMIN")
.anyRequest().authenticated()
).formLogin(
form -> form
.loginPage("/login")
.defaultSuccessUrl("/index")
.usernameParameter("username")
.passwordParameter("password")
.permitAll()
).logout(
logout -> logout
.logoutRequestMatcher(new AntPathRequestMatcher("/checkout"))
.permitAll()
);
return http.build();
}

最新更新