SpringBoot整合SpringSecurit实现ajax的登录、退出、权限校验
在Spring Boot整合Spring Security实现AJAX登录、登出及权限检查的核心步骤如下:
- 添加Spring Security依赖。
- 配置Spring Security。
- 创建登录和登出的Controller。
- 添加AJAX登录和登出的JavaScript代码。
- 添加权限检查的注解。
以下是实现上述功能的示例代码:
pom.xml添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
SecurityConfig.java配置Spring Security:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable() // 禁用CSRF保护
.authorizeRequests()
.antMatchers("/login").permitAll() // 允许登录页面
.anyRequest().authenticated() // 其他请求需要认证
.and()
.formLogin() // 启用表单登录
.loginProcessingUrl("/doLogin") // 指定登录处理URL
.successHandler(ajaxAuthenticationSuccessHandler()) // 登录成功处理
.failureHandler(ajaxAuthenticationFailureHandler()); // 登录失败处理
}
@Bean
public AuthenticationSuccessHandler ajaxAuthenticationSuccessHandler() {
return (request, response, authentication) -> response.setStatus(HttpStatus.OK.value());
}
@Bean
public AuthenticationFailureHandler ajaxAuthenticationFailureHandler() {
return (request, response, exception) -> response.setStatus(HttpStatus.UNAUTHORIZED.value());
}
}
UserController.java添加AJAX登录和登出:
@RestController
public class UserController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@PostMapping("/login")
public ResponseEntity<?> login(@RequestParam String username, @RequestParam String password) {
try {
Authentication authentication = authenticationManager.authenticate(
评论已关闭