gpt4 book ai didi

java - SpringSecurity - SecurityConfiguration.java - HttpSecurity - 不工作

转载 作者:行者123 更新时间:2023-12-01 12:38:03 25 4
gpt4 key购买 nike

我正在尝试将 Spring Security 实现到我的基于 MVC Maven 的项目,并已包含 Spring Boot。

我有工作前端和后端,但直到现在我都在使用假登录 - 我只是通过 JS 和 AngularJS 确定用户数据(例如用户名和密码)的范围,并将其发送到后端 Controller ,其中数据来自数据库通过 DAO 层检索,并在发送女巫响应后与范围信息进行比较 - 如果“OK”,我将用户转发到用户主页,反之亦然。这意味着,如果我运行我的应用程序并直接在浏览器栏输入 localhost:8080/#/user (只有登录的用户才能看到的页面),我可以毫无问题地访问它.

现在,当业务逻辑层测试完成后,就到了实现 Spring Security 的时候了。

我仍在尝试理解 Spring Security 并尝试正确编写 SecurityConfiguration.java 文件 - 将其设置为不会让任何人访问 book.html 和 user.html 页面,并最终重定向此类用户登录.html。

这是我的 SecurityConfiguration.java 文件:

@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

@Resource
private DataSource dataSource;

@Bean
public BCryptPasswordEncoder PasseordEncoder() {
return new BCryptPasswordEncoder();
}

protected void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
JdbcUserDetailsManager userDetailsService = new JdbcUserDetailsManager();
userDetailsService.setDataSource(dataSource);
PasswordEncoder encoder = new BCryptPasswordEncoder();

auth.userDetailsService(userDetailsService).passwordEncoder(encoder);
auth.jdbcAuthentication().dataSource(dataSource);

if (!userDetailsService.userExists("user")) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("USER"));
User userDetails = new User("user", encoder.encode("password"),
authorities);

userDetailsService.createUser(userDetails);
}

}

protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/user").access("hasRole('USER')")
.antMatchers("/book").access("hasRole('USER')");
}

}

但是当我运行应用程序并尝试访问例如/user 时,它允许我这样做!有人可以帮助我了解我该怎么做,以及如何解决这个问题并通过第一步吗?

最佳答案

我认为您忘记声明身份验证的入口点。正如您在评论中指出的,您需要将 .and().formLogin().loginPa‌​ge("collections/login") 添加到 http.authorizeRequests().

但是,您还需要授权对登录页面进行未经身份验证的访问,以避免重定向循环:询问页面 -> 需要身份验证 -> 重定向到登录页面 -> 需要身份验证 -> 重定向...

您应该简单地遵循以下有关 Java 配置和表单登录的引用手册示例:

protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll();
}

使用您的代码,它给出:

protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/user").access("hasRole('USER')")
.antMatchers("/book").access("hasRole('USER')")
.and().formLogin().loginPage("/collections/login").permitAll();
}

最后备注:请注意登录网址前面的/如果您希望从 / 以外的任何页面找到您的登录页面,请始终使用绝对路径!

关于java - SpringSecurity - SecurityConfiguration.java - HttpSecurity - 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25386738/

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