(1)引入Spring Security 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
(2)编写Spring Security 配置类
package com.zhang.travel.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.loginPage("/backstage/admin_login")
.usernameParameter("username")
.passwordParameter("password")
.loginProcessingUrl("/backstage/admin/login")
.successForwardUrl("/backstage/index")
.failureForwardUrl("/backstage/admin_fail");
http.authorizeRequests()
.antMatchers("/backstage/admin/login").permitAll()
.antMatchers("/backstage/admin_fail").permitAll()
.antMatchers("/backstage/admin_login").permitAll()
.antMatchers("/**/*.css", "/**/*.js").permitAll()
.antMatchers("/backstage/**").authenticated()
.antMatchers("/frontdesk/**").permitAll();
http.logout()
.logoutUrl("/backstage/admin/logout")
.logoutSuccessUrl("/backstage/admin_login")
.clearAuthentication(true)
.invalidateHttpSession(true);
http.exceptionHandling()
.accessDeniedHandler(new MyAccessDeniedHandler());
http.csrf().disable();
http.cors();
super.configure(http);
}
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
(3)自定义认证逻辑
@Service
public class MyUserDetailService implements UserDetailsService {
@Autowired
private AdminService adminService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Admin admin = adminService.findByAdminName(username);
if (admin == null) {
throw new UsernameNotFoundException("用户不存在");
}
if (!admin.isStatus()){
throw new UsernameNotFoundException("用户不可用");
}
List<Permission> permissions = adminService.findAllPermission(username);
List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
for (Permission permission : permissions) {
grantedAuthorities.add(new SimpleGrantedAuthority(permission.getPermissionDesc()));
}
UserDetails userDetails = User.withUsername(admin.getUsername())
.password(admin.getPassword())
.authorities(grantedAuthorities)
.build();
return userDetails;
}
}