一 . 尝试引入SpringSecurity:
idea新建project勾选springweb 和 security两个选项,然后写一个Controller如下:
@RestController public class HelloController { /** * @Author zhangzuorui * @Description 测试接口 * @Param * @return **/ @GetMapping("/helloService") public String HelloService(){ return "this is HelloService"; } }
启动项目:
2020-04-14 14:44:22.734 INFO 3264 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2020-04-14 14:44:22.734 INFO 3264 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 673 ms 2020-04-14 14:44:22.839 INFO 3264 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor' 2020-04-14 14:44:22.950 INFO 3264 --- [ main] .s.s.UserDetailsServiceAutoConfiguration : Using generated security password: 8869e50c-a7db-4626-ae3f-cacccbe094cd 2020-04-14 14:44:23.002 INFO 3264 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@21ab988f, org.springframework.security.web.context.SecurityContextPersistenceFilter@175acfb2, org.springframework.security.web.header.HeaderWriterFilter@5d39f2d8, org.springframework.security.web.csrf.CsrfFilter@278f8425, org.springframework.security.web.authentication.logout.LogoutFilter@59942b48, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@4650a407, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@46c00568, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter@29314cc9, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@6edaa77a, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@4e868ef5, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@2f879bab, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@4e38d975, org.springframework.security.web.session.SessionManagementFilter@55ea2d70, org.springframework.security.web.access.ExceptionTranslationFilter@69cac930, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@abbc908] 2020-04-14 14:44:23.042 INFO 3264 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' 2020-04-14 14:44:23.044 INFO 3264 --- [ main] c.s.t.TestsecurityApplication : Started TestsecurityApplication in 1.293 seconds (JVM running for 2.316) 2020-04-14 14:44:49.454 INFO 3264 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet' 2020-04-14 14:44:49.454 INFO 3264 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet' 2020-04-14 14:44:49.458 INFO 3264 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 4 ms
可以看到启动后有一个security-password,这个是security自带的初始密码,用于访问接口localhost:8080/helloService时使用(用户名:user)。
当然项目使用中,我们还是要进行用户名和密码配置的,所以我们可以在application.properties文件中进行设置:
spring.security.user.name=zzr spring.security.user.password=123456
重启后再访问接口输入设置的用户名密码即可访问接口。
二. 服务端配置类
/** * @ClassName SecurityConfig * @Description TODO * @Author lenovo * @Date 2020/4/14 18:09 * @Version 1.0 */ //ctrl+H查看接口或者类方法 public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private PasswordEncoder passwordEncoder; @Bean PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(6); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("zzr") .password("123456") .roles("admin"); /*.and().withUser("XXX");如果需要配置多个用户,用 and 相连。 * 配置过后,application.properties的设置就无效了 * inMemoryAuthentication表示在内存中 * */ } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login.html") .permitAll() .and() .csrf().disable(); /** *1.如果我们使用 XML 来配置 Spring Security , 里边会有一个重要的标签 <http>,HttpSecurity 提供的配置方法 都对应了该标签。 2.authorizeRequests 对应了 <intercept-url>。 3.formLogin 对应了 <formlogin>。 4.and 方法表示结束当前标签,上下文回到HttpSecurity,开启新一轮的配置。 5.permitAll 表示登录相关的页面/接口不要被拦截。 6.最后记得关闭 csrf */ } @Override public void configure(WebSecurity web) throws Exception { /*忽略一些静态文件url地址*/ web.ignoring().antMatchers("/js/**", "/css/**","/images/**"); } }
新增类SecurityConfig配置类:
当我们定义了登录页面为 /login.html 的时候,Spring Security 也会帮我们自动注册一个 /login.html 的接口,这个接口是 POST 请求,用来处理登录逻辑。