import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
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;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/user/**").hasAnyRole("USER","ADMIN")//user下的资源USER和ADMIN权限才可以访问
.and()
.authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN")//只有ADMIN角色才能访问
.and()
.authorizeRequests()
.antMatchers("/").permitAll()
.and()
.httpBasic()
.and()
.logout()
.permitAll();
http.csrf().disable(); //取消csrf防护
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth //配置角色密码
.inMemoryAuthentication()
.passwordEncoder(new BCryptPasswordEncoder()).withUser("admin").password(new BCryptPasswordEncoder().encode("admin")).roles("ADMIN")
.and()
.passwordEncoder(new BCryptPasswordEncoder()).withUser("user").password(new BCryptPasswordEncoder().encode("user")).roles("USER");
}
}
springboot使用springsecurity权限访问配置
最新推荐文章于 2023-10-24 11:45:40 发布