【发布时间】:2026-02-15 15:55:02
【问题描述】:
登录成功,但即使我授予了 USER 的访问权限,spring security 也会阻止 url。我该如何管理这件事?
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication().withUser("sahil").password("123")
.roles("ADMIN","USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login").permitAll()
.antMatchers("/welcome","/inventory/**","/sales/**").access("hasRole('USER')")
.and()
.csrf().disable();
}
LoginController.java
@Controller
public class LoginController {
@RequestMapping(value = { "/", "/login" }, method = RequestMethod.GET)
public String showLoginPage() {
return "login";
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String handleUserLogin(ModelMap model, @RequestParam String name, @RequestParam String password) {
if (!service.validateUser(name, password)) {
model.put("errorMsg", "Invalid Credential");
return "login";
}
System.out.println("principal : " + getLoggedInUserName());
model.put("name", name);
model.put("password", password);
return "welcome";
}
private String getLoggedInUserName() {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
System.out.println("in if");
return ((UserDetails)principal).getUsername();
} else {
System.out.println("in else");
return principal.toString();
}
}
@RequestMapping(value = "/welcome", method = RequestMethod.GET)
public String showWelcomeDashboard() {
return "welcome";
}
}
1 . 一旦登录成功页面重定向到欢迎页面,但 url 仍然是 localhost:8080/login 而不是 localhost:8080/welcome .
2. 重定向到 URL localhost:8080/sales 之后是不是 403 Access denied.
【问题讨论】:
-
嗨,试着把这个 .access("hasRole('USER')") 改成这个 .access("ROLE_USER")
-
@Error java.lang.IllegalArgumentException: 无法评估表达式'ROLE_USER'
-
@PraveenKumarLalasangi :我已经尝试过了,我添加了更多说明,请您现在查看
标签: java spring spring-mvc spring-security access-denied