spring security
public class CreateUser extends User {
private String userId;
private String deptId;
public CreateUser(String deptId,String userId,String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection extends GrantedAuthority> authorities) {
super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
this.deptId = deptId;
this.userId = userId;
}
}
@lombok
public class UserInfo implements Serializable {
private String userId;
private String username;
private String password;
private String deptId;
private Boolean delFlag;
}
@Service
public class PermissionServiceImpl implements PermissionService {
@Override
public List getPermission(String username) {
ArrayList xxs = new ArrayList<>();
return xxs;
}
}
@Service
public class UserServiceImpl implements UserService {
@Override
public UserInfo getUserByName(String username) {
UserInfo userInfo = new UserInfo();
userInfo.setUserId("userid_1");
userInfo.setUsername(username);
userInfo.setPassword("123");
userInfo.setDeptId("deptid_1");
userInfo.setDelFlag(false);
return userInfo;
}
}
public interface PermissionService {
List getPermission(String username);
}
public interface UserService {
UserInfo getUserByName(String username);
}
@Service
@RequiredArgsConstructor
public class DbUserDetailsService implements UserDetailsService {
@Autowired
private UserService userService;
@Autowired
private PermissionService permissionService;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserInfo userInfo = userService.getUserByName(username);
String cryptPwd = passwordEncoder.encode(userInfo.getPassword());
userInfo.setPassword(cryptPwd);
// 查询权限, 把权限数据封装到 authorities 的集合里面
List extends GrantedAuthority> authorities = AuthorityUtils
.createAuthorityList(permissionService.getPermission(username).toArray(new String[0]));
return new CreateUser(
userInfo.getDeptId(),
userInfo.getUserId(),
username,
userInfo.getPassword(),
!userInfo.getDelFlag(), // 注意这里是非
true,
true,
true,
authorities
);
}
}
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true,jsr250Enabled = true,prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
}
@Configuration
@EnableWebSecurity //启用Web安全功能
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Autowired
private DbUserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
//访问"/"和"/home"路径的请求都允许
.antMatchers("/", "/home","/staff","/staff/*")
.permitAll()
//而其他的请求都需要认证(登录)
.anyRequest()
.authenticated()
.and()
//修改Spring Security默认的登陆界面
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
// 构建用户信息存储的方式
// 基于内存的方式
@Override
protected void configure(AuthenticationManagerBuilder builder) throws Exception{
builder.userDetailsService(userDetailsService);
}
}
@Controller
public class SecurityController {
@GetMapping(value = {"/home","/"})
public String home(){
return "home";
}
@GetMapping(value = "/hello")
public String hello(){
return "hello";
}
@GetMapping(value = "/login")
public String login(){
return "login";
}
@GetMapping(value = "/admin")
@Secured("ROLE_ADMIN")
public String admin(){
return "admin";
}
}
@Slf4j
@Component
public class TimeFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
log.info("time filter init");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
log.info("time filter start");
long start = System.currentTimeMillis();
filterChain.doFilter(servletRequest,servletResponse);
log.info("time filter: " + (System.currentTimeMillis() - start));
log.info("time filter finish");
}
@Override
public void destroy() {
log.info("time filter destroy");
}
}
@SpringBootApplication
public class SecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SecurityApplication.class, args);
}
}
admin.html
admin page
Hello.html
Hello [[${#httpServletRequest.remoteUser}]]!
home.html
Welcome!
Click here to see a greeting.
login.html
Invalid username and password.
You have been logged out.
4.0.0 org.springframework.boot spring-boot-starter-parent 2.4.4 com.example security 0.0.1-SNAPSHOT security learn security 1.8 org.springframework.boot spring-boot-starter-security org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-thymeleaf 2.4.4 org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test org.springframework.security spring-security-test test org.springframework.boot spring-boot-maven-plugin org.projectlombok lombok



