SpringBoot中怎么整合SpringSecurity,很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來(lái)學(xué)習(xí)下,希望你能有所收獲。
org.springframework.boot spring-boot-starter-security
@RestController public class HelloController { @GetMapping("/hello") public String hello() { return "Hello"; } }
訪問(wèn)http://localhost:8080/hello 會(huì)自動(dòng)跳到login頁(yè)面
默認(rèn)用戶名 user
默認(rèn)密碼在控制臺(tái)顯示
spring.security.user.name=user spring.security.user.password=123 spring.security.user.roles=admin
新建一個(gè)SecurityConfig .java類
@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { //去掉spring5一定要密碼加密的限制 @Bean PasswordEncoder passwordEncoder(){ return NoOpPasswordEncoder.getInstance(); } //第二種: 在代碼中配置用戶名和密碼 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("terry").password("123").roles("admin") .and() .withUser("tt").password("456").roles("user"); } }
@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { //去掉spring5一定要密碼加密的限制 @Bean PasswordEncoder passwordEncoder(){ return NoOpPasswordEncoder.getInstance(); } //第二種: 在代碼中配置用戶名和密碼 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("terry").password("123").roles("admin") .and() .withUser("tt").password("456").roles("user"); } //HttpSecurity配置 @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/**").hasRole("admin") .antMatchers("/user/**").hasAnyRole("admin","user") //.antMatchers("/user/**").access("hasAnyRole('user','admin')") .anyRequest().authenticated() .and() .formLogin() .loginProcessingUrl("/doLogin") .permitAll() .and() .csrf().disable();//要使用postman,防止被認(rèn)為是csrf攻擊 } }
@RequestMapping("/admin/hello") public String admin(){ return "Hello admin"; } @RequestMapping("/user/hello") public String user(){ return "hello user"; }
看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注創(chuàng)新互聯(lián)-成都網(wǎng)站建設(shè)公司行業(yè)資訊頻道,感謝您對(duì)創(chuàng)新互聯(lián)的支持。