maven 导 security包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
配置 注解
@Configuration //@EnableWebSecurity 有配置时就不需要了 public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean 密码 public PasswordEncoder getPasswordEncoder() { return new BCryptPasswordEncoder(); } @Autowired private DataSource datasource; @Override protected void configure(HttpSecurity http) throws Exception { http.formLogin() // 表单登陆 .loginPage("/login") // 登陆页面 .defaultSuccessUrl("/index") .failureUrl("/login?error") .permitAll() // 放行 .and() .rememberMe() .tokenValiditySeconds(1209600) .key("mykey") .and() .logout() .logoutUrl("/logout") .logoutSuccessUrl("/logout-success") .permitAll() .and().authorizeRequests() // 权限管理 .antMatchers("/login").permitAll() .antMatchers("/admin/**").hasRole("ROLE_ADMIN") .antMatchers("/user/**").hasRole("ROLE_USER") .anyRequest().authenticated(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .userDetailsService(userService); // 从内存中获取用户名 //.inMemoryAuthentication().withUser("mxz").password("mxz").roles("admin") //.and().and() // 从数据库中获取用户 角色 //.jdbcAuthentication().dataSource(datasource) // .usersByUsernameQuery("select user_name,password from users where user_name = ?"); }
实体类实现 userDetail
服务类 实现 UserDetailService