问题:
解决:
运行后,访问 http://localhost:8080/user/user1 会跳转到 登陆页,用 test1 / 123456 登陆后可以查看
App.java
|
package demo.security1; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class App { public static void main(String[] argv) { SpringApplication.run(App.class, argv); } } |
WebSecurityConfig.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
package demo.security1; import org.springframework.beans.factory.annotation.Autowired; 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.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.User; @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override public void configure(HttpSecurity web) throws Exception { web.authorizeRequests() .antMatchers("/test/**", "/").permitAll() .antMatchers("/user/**").hasRole("user") .anyRequest().authenticated() .and().formLogin() .and().httpBasic(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser(User.withDefaultPasswordEncoder().username("test1").password("123456").roles("user")); } } |
TestController.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
package demo.security1; import java.security.Principal; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { @RequestMapping("/test/test1") public String test1() { return "test1"; } @RequestMapping("/") public String welcome(Principal p) { return String.format("welcome %s", p.getName()); } @RequestMapping("/user/user1") public String user1() { return "user1"; } } |
参考:
https://docs.spring.io/spring-security/site/docs/5.0.2.RELEASE/reference/htmlsingle/#getting-started
https://github.com/spring-projects/spring-security/blob/5.0.2.RELEASE/samples/boot/helloworld/src/main/java/org/springframework/security/samples/config/SecurityConfig.java