一 初体验有spring cloud b2b2c电子商务需求的朋友可以加企鹅求求:一零三八七七四六二六
1.导包
<span style="font-size: 14px;"><dependency><br> <groupId>org.springframework.boot</groupId><br> <artifactId>spring-boot-starter-security</artifactId><br></dependency><br></span>2.测试
<span style="font-size: 14px;">@RestController<br>public class HelloController<br>{<br> @GetMapping("/hello")<br> public String hello() {<br> return "Hello";<br> }<br>}<br></span>访问http://localhost:8080/hello 会自动跳到login页面
默认用户名 user
默认密码在控制台显示
二 在配置文件或代码中配置security需要的用户名和密码
第一种: 在配置文件中配置
<span style="font-size: 14px;">spring.security.user.name=user<br>spring.security.user.password=123<br>spring.security.user.roles=admin<br></span>第二种:在代码中配置
新建一个SecurityConfig .java类
<span style="font-size: 14px;">@Configuration<br>public class SecurityConfig extends WebSecurityConfigurerAdapter<br>{<br> //去掉spring5一定要密码加密的限制<br> @Bean<br> PasswordEncoder passwordEncoder(){<br> return NoOpPasswordEncoder.getInstance();<br> }<br> //第二种: 在代码中配置用户名和密码<br> @Override<br> protected void configure(AuthenticationManagerBuilder auth) throws Exception<br> {<br> auth.inMemoryAuthentication()<br> .withUser("terry").password("123").roles("admin")<br> .and()<br> .withUser("tt").password("456").roles("user");<br> }<br>}<br></span>三 配置HttpSecurity
1.接着上面的配置文件写
<span style="font-size: 14px;">@Configuration<br>public class SecurityConfig extends WebSecurityConfigurerAdapter<br>{<br> //去掉spring5一定要密码加密的限制<br> @Bean<br> PasswordEncoder passwordEncoder(){<br> return NoOpPasswordEncoder.getInstance();<br> }<br> //第二种: 在代码中配置用户名和密码<br> @Override<br> protected void configure(AuthenticationManagerBuilder auth) throws Exception<br> {<br> auth.inMemoryAuthentication()<br> .withUser("terry").password("123").roles("admin")<br> .and()<br> .withUser("tt").password("456").roles("user");<br> }<br><br> //HttpSecurity配置<br> @Override<br> protected void configure(HttpSecurity http) throws Exception<br> {<br> http.authorizeRequests()<br> .antMatchers("/admin/**").hasRole("admin")<br> .antMatchers("/user/**").hasAnyRole("admin","user")<br> //.antMatchers("/user/**").access("hasAnyRole('user','admin')")<br> .anyRequest().authenticated()<br> .and()<br> .formLogin()<br> .loginProcessingUrl("/doLogin")<br> .permitAll()<br> .and()<br> .csrf().disable();//要使用postman,防止被认为是csrf攻击<br> }<br>}<br></span>2.测试
<span style="font-size: 14px;">@RequestMapping("/admin/hello")<br>public String admin(){<br> return "Hello admin";<br>}<br><br>@RequestMapping("/user/hello")<br>public String user(){<br> return "hello user";<br>}<br></span>