以下回答参考 皆我百晓生、券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。
要解决这个问题,首先确保你的Spring Boot项目中已经正确地配置了@EnableWebSecurity
注解。如果还没有,请添加以下代码:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// 设置允许所有用户访问的URL
http.authorizeRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated();
// 使用JWT令牌验证
http.csrf().disable();
http.headers().frameOptions().disable();
http.oauth2Login();
}
}
接下来,你需要在你的Maven项目中创建一个名为web.xml
的文件,并添加以下配置:
<web-app>
<servlet>
<servlet-name>springSecurityFilterChain</servlet-name>
<servlet-class>org.springframework.web.filter.DelegatingFilterProxy</servlet-class>
<init-param>
<param-name>filterProcessesUrl</param-name>
<param-value>/login/*</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springSecurityFilterChain</servlet-name>
<url-pattern>/login/*</url-pattern>
</servlet-mapping>
<!-- 其他过滤器 -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.security.config.annotation.web.servlet.config.WebMvcConfigurerAdapter</filter-class>
<init-param>
<param-name>authenticationManagerBeanName</param-name>
<param-value>authenticationManager</param-value>
</init-param>
<init-param>
<param-name>addFormAuthenticationSuccessHandlerClass</param-name>
<param-value>org.springframework.security.web.authentication.RedirectHttpEntryPoint</param-value>
</init-param>
</filter>
</web-app>
现在,你可以在控制器或视图中使用@PreAuthorize
注解来检查用户的权限。
例如,在一个控制器方法上添加@PreAuthorize("hasRole('ROLE_ADMIN')")
和@PreAuthorize("hasRole('ROLE_USER')")
:
@PostMapping("/admin")
public String adminPage() {
return "admin-page";
}
@PostMapping("/user")
public String userList() {
return "user-list";
}
这样,只有具有ROLE_ADMIN
角色的用户才能访问admin-page
,而具有ROLE_USER
角色的用户只能访问user-list
。
如果你希望对特定的资源进行更细粒度的控制,你可以使用@PreAuthorize
注解结合Spring MVC的@PathVariable
、@RequestParam
等注解。例如,如果你想限制某些资源只对管理员显示,你可以这样做:
@GetMapping("/restricted")
public String restricted(@PathVariable String userId, Model model) {
if (!userId.equals("admin")) {
throw new ForbiddenException("Access denied");
}
model.addAttribute("message", "Welcome to the restricted area!");
return "restricted";
}
这将确保只有当userId
为admin
时,才能访问restricted
页面。