springboot整合springbootSecurity

tech2024-12-28  5

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"); //防止网站被攻击,现在关闭csrf功能,登录失败的原因 http.csrf().disable(); //注销/logout,并跳转页面 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"); } }
最新回复(0)