Spring Security
和 Apache Shiro
都是安全框架,爲Java應用程序提供身份認證和受權。css
重
量級安全框架輕
量級安全框架關於shiro的權限認證與受權可參考小編的另一篇文章 : SpringBoot集成Shiro 實現動態加載權限java
https://blog.csdn.net/qq_38225558/article/details/101616759git
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
@RestController public class IndexController { @GetMapping("/index") public String index() { return "Hello World ~"; } }
舒適小提示:在不進行任何配置的狀況下,Spring Security 給出的默認用戶名爲user
密碼則是項目在啓動運行時隨機生成的一串字符串,會打印在控制檯,以下圖:
當咱們訪問index首頁的時候,系統會默認跳轉到login頁面進行登陸認證web
認證成功以後纔會跳轉到咱們的index頁面
spring
除了上面Spring Security在不進行任何配置下默認給出的用戶user
密碼隨項目啓動生成隨機字符串,咱們還能夠經過如下方式配置數據庫
spring: security: user: name: admin # 用戶名 password: 123456 # 密碼
新建Security 核心配置類繼承WebSecurityConfigurerAdapter
json
@Configuration @EnableWebSecurity // 啓用Spring Security的Web安全支持 public class SecurityConfig extends WebSecurityConfigurerAdapter { /** * 將用戶設置在內存中 * @param auth * @throws Exception */ @Autowired public void config(AuthenticationManagerBuilder auth) throws Exception { // 在內存中配置用戶,配置多個用戶調用`and()`方法 auth.inMemoryAuthentication() .passwordEncoder(passwordEncoder()) // 指定加密方式 .withUser("admin").password(passwordEncoder().encode("123456")).roles("ADMIN") .and() .withUser("test").password(passwordEncoder().encode("123456")).roles("USER"); } @Bean public PasswordEncoder passwordEncoder() { // BCryptPasswordEncoder:Spring Security 提供的加密工具,可快速實現加密加鹽 return new BCryptPasswordEncoder(); } }
這種方式也就是咱們項目中一般使用的方式,這個留到後面的文章再說跨域
相關代碼都有註釋相信很容易理解安全
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { /** * 登陸處理 * @param http * @throws Exception */ @Override protected void configure(HttpSecurity http) throws Exception { // 開啓登陸配置 http.authorizeRequests() // 標識訪問 `/index` 這個接口,須要具有`ADMIN`角色 .antMatchers("/index").hasRole("ADMIN") // 容許匿名的url - 可理解爲放行接口 - 多個接口使用,分割 .antMatchers("/", "/home").permitAll() // 其他全部請求都須要認證 .anyRequest().authenticated() .and() // 設置登陸認證頁面 .formLogin().loginPage("/login") // 登陸成功後的處理接口 - 方式① .loginProcessingUrl("/home") // 自定義登錄用戶名和密碼屬性名,默認爲 username和password .usernameParameter("username") .passwordParameter("password") // 登陸成功後的處理器 - 方式② // .successHandler((req, resp, authentication) -> { // resp.setContentType("application/json;charset=utf-8"); // PrintWriter out = resp.getWriter(); // out.write("登陸成功..."); // out.flush(); // }) // 配置登陸失敗的回調 .failureHandler((req, resp, exception) -> { resp.setContentType("application/json;charset=utf-8"); PrintWriter out = resp.getWriter(); out.write("登陸失敗..."); out.flush(); }) .permitAll()//和表單登陸相關的接口通通都直接經過 .and() .logout().logoutUrl("/logout") // 配置註銷成功的回調 .logoutSuccessHandler((req, resp, authentication) -> { resp.setContentType("application/json;charset=utf-8"); PrintWriter out = resp.getWriter(); out.write("註銷成功..."); out.flush(); }) .permitAll() .and() .httpBasic() .and() // 關閉CSRF跨域 .csrf().disable(); } /** * 忽略攔截 * @param web * @throws Exception */ @Override public void configure(WebSecurity web) throws Exception { // 設置攔截忽略url - 會直接過濾該url - 將不會通過Spring Security過濾器鏈 web.ignoring().antMatchers("/getUserInfo"); // 設置攔截忽略文件夾,能夠對靜態資源放行 web.ignoring().antMatchers("/css/**", "/js/**"); } }
WebSecurityConfigurerAdapter