配置类:SecurityConfig.java
package com.example.spring_security.config; import com.example.spring_security.controller.RouterController; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; 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; // Aop式编程 @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { // 首页所有人可以访问,功能页只有对应有权限的人可以访问 //它是链式编程 // 授权 http.authorizeRequests().antMatchers("http://www.likecs.com/").permitAll() .antMatchers("/level1/**").hasRole("vip1") .antMatchers("/level2/**").hasRole("vip2") .antMatchers("/level3/**").hasRole("vip3"); //认证请求 // 没有权限,进入就需要登录 http.formLogin(); //开启注销功能 并跳转到首页 http.logout().logoutSuccessUrl("http://www.likecs.com/"); // springSecurity为了防止网站攻击 默认开启了csrf功能 // http.csrf().disable(); } // 认证 springboot 2.1.x 可以直接使用 // 密码编码: PasswordEncoder 没有编码的错误~! // 如果没有密码编码服务器会报500错误 :.withUser("guest").password("guest").roles("vip1"); // 对他进行加密之后:new BCryptPasswordEncoder().encode("curry") @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("ahui").password(new BCryptPasswordEncoder().encode("curry")).roles("vip2","vip3") .and() .withUser("admin").password(new BCryptPasswordEncoder().encode("admin")).roles("vip2","vip3","vip1") .and() .withUser("guest").password(new BCryptPasswordEncoder().encode("guest")).roles("vip1"); } }走进springboot (4)
内容版权声明:除非注明,否则皆为本站原创文章。