1. pom.xml
<dependency>
<groupId>org.springframework.boot
</groupId>
<artifactId>spring-boot-starter-security
</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot
</groupId>
<artifactId>spring-boot-starter-thymeleaf
</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot
</groupId>
<artifactId>spring-boot-starter-web
</artifactId>
</dependency>
2. 配置security
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http
) throws Exception
{
http
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/toAdminIndex").hasRole("admin")
.antMatchers("/toGuestIndex").hasRole("guest");
http
.formLogin().loginPage("/toLogin").usernameParameter("user").passwordParameter("pwd").loginProcessingUrl("/login");
http
.csrf().disable();
http
.logout().logoutSuccessUrl("/");
http
.rememberMe().rememberMeParameter("remember");
}
@Override
protected void configure(AuthenticationManagerBuilder auth
) throws Exception
{
auth
.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("admin","guest")
.and()
.withUser("user1").password(new BCryptPasswordEncoder().encode("123456")).roles("gust");
}
}