demo已提交git https://gitee.com/q975583865/springSecurityDemo
1.导入jar
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2.继承 UserDetailsService 实现 loadUserByUsername
import cn.test.bean.Auth;
import cn.test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UserService userService;
/**
* 授权的时候是对角色授权,而认证的时候应该基于资源,而不是角色,因为资源是不变的,而用户的角色是会变的
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
cn.test.bean.User sysUser = userService.getUserByName(username);
if (null == sysUser) {
throw new UsernameNotFoundException(username);
}
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
List<Auth> userAuthL = userService.getUserAuth(sysUser.getId());
for(Auth auth:userAuthL){
authorities.add(new SimpleGrantedAuthority(auth.getAuthCode()));
}
return new User(sysUser.getUsername(), sysUser.getPassword(), authorities);
}
}
3.继承 WebSecurityConfigurerAdapter
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 启用方法级别的权限认证
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyUserDetailsService myUserDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
// 允许所有用户访问"/"和"/index.html"
http.authorizeRequests()
.antMatchers("/", "/index.html").permitAll()
.anyRequest().authenticated() // 其他地址的访问均需验证权限
.and()
.formLogin()
.loginProcessingUrl("/login")
.and()
.logout()
.logoutSuccessUrl("/index.html");
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(myUserDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
controller测试
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Collection;
@RestController
public class HelloController {
//获取当前登录用户的权限集
@GetMapping("/getCurrentUserAuth")
public void getCurrentUserAuth() {
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
.getAuthentication()
.getPrincipal();
Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
System.out.println("当前账号用户名:"+userDetails.getUsername());
for (GrantedAuthority grantedAuthority : authorities) {
System.out.println("当前账号权限集:" + grantedAuthority.getAuthority());
}
}
@PreAuthorize("hasAuthority('UserIndex')")
@GetMapping("/one")
public String one() {
return "OK";
}
//常用 @PreAuthorize("hasAuthority('')")
@PreAuthorize("hasAuthority('caidan')")
@GetMapping("/two")
public String two() {
return "OK";
}
//满足一个权限就可以了,不常用
@PreAuthorize("hasAnyAuthority('caidan','UserIndex')")
@GetMapping("/three")
public String three() {
return "OK";
}
}