SpringBoot集成Security

1-項(xiàng)目創(chuàng)建

創(chuàng)建SpringBoot項(xiàng)目。

2-引入依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
引入依賴后,項(xiàng)目的所有接口都會(huì)被保護(hù)起來。

3-編寫HelloController

@RestController
public class HelloController {
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }
}

4-訪問/hello,需要登錄后才可以訪問

默認(rèn)情況,用戶名是user,密碼在控制臺(tái)隨機(jī)生成。

5-通過配置文件配置用戶名密碼(可選)

spring.security.user.name=chadj
spring.security.user.password=123456

6-通過Java配置用戶名密碼(可選)

創(chuàng)建SecurityConfig
    @Configuration
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            // 下面這兩行配置表示在內(nèi)存中配置了兩個(gè)用戶
            auth.inMemoryAuthentication()
                    .withUser("chadj").roles("admin").password("$2a$10$OR3VSksVAmCzc.7WeaRPR.t0wyCsIj24k0Bne8iKWV1o.V9wsP8Xe")
                    .and()
                    .withUser("jichengda").roles("user").password("$2a$10$p1H8iWa8I4.CA.7Z8bwLjes91ZpY.rYREGHQEInNtAp4NzL6PLKxi");
        }
        @Bean
        PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }
    }

7-登錄配置

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    VerifyCodeFilter verifyCodeFilter;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(verifyCodeFilter, UsernamePasswordAuthenticationFilter.class);
        http
        .authorizeRequests()//開啟登錄配置
        .antMatchers("/hello").hasRole("admin")//表示訪問 /hello 這個(gè)接口,需要具備 admin 這個(gè)角色
        .anyRequest().authenticated()//表示剩余的其他接口,登錄之后就能訪問
        .and()
        .formLogin()
        //定義登錄頁面,未登錄時(shí),訪問一個(gè)需要登錄之后才能訪問的接口,會(huì)自動(dòng)跳轉(zhuǎn)到該頁面
        .loginPage("/login_p")
        //登錄處理接口
        .loginProcessingUrl("/doLogin")
        //定義登錄時(shí),用戶名的 key,默認(rèn)為 username
        .usernameParameter("uname")
        //定義登錄時(shí),用戶密碼的 key,默認(rèn)為 password
        .passwordParameter("passwd")
        //登錄成功的處理器
        .successHandler(new AuthenticationSuccessHandler() {
            @Override
            public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write("success");
                    out.flush();
                }
            })
            .failureHandler(new AuthenticationFailureHandler() {
                @Override
                public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException exception) throws IOException, ServletException {
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write("fail");
                    out.flush();
                }
            })
            .permitAll()//和表單登錄相關(guān)的接口統(tǒng)統(tǒng)都直接通過
            .and()
            .logout()
            .logoutUrl("/logout")
            .logoutSuccessHandler(new LogoutSuccessHandler() {
                @Override
                public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write("logout success");
                    out.flush();
                }
            })
            .permitAll()
            .and()
            .httpBasic()
            .and()
            .csrf().disable();
    }
}

8-忽略攔截

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/vercode");
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 一、Spring security框架簡(jiǎn)介 Spring Security是Spring社區(qū)的一個(gè)頂級(jí)項(xiàng)目,也是S...
    zenghi閱讀 1,540評(píng)論 0 3
  • 前言 本章內(nèi)容: ??Spring Security介紹 ??使用Servlet規(guī)范中的Filter保護(hù)Web應(yīng)用...
    Chandler_玨瑜閱讀 7,509評(píng)論 0 68
  • 我們?cè)诰帉慦eb應(yīng)用時(shí),經(jīng)常需要對(duì)頁面做一些安全控制,比如:對(duì)于沒有訪問權(quán)限的用戶需要轉(zhuǎn)到登錄表單頁面。要實(shí)現(xiàn)訪問...
    程序猿DD閱讀 23,387評(píng)論 6 32
  • 過了今晚就三十了 以前覺得很遙遠(yuǎn) 現(xiàn)在就在眼前 一大早媽媽就打來電話 都說兒生母苦 當(dāng)我做了媽媽后 體會(huì)更深刻了 ...
    Melshow閱讀 169評(píng)論 0 0
  • 001 建立合理的資產(chǎn)配置計(jì)劃。 學(xué)會(huì)配置自己的資產(chǎn),讓錢去生錢。可以根據(jù)自己本身的情況來進(jìn)行資產(chǎn)配置,我計(jì)劃將收...
    影殊穎閱讀 226評(píng)論 0 0

友情鏈接更多精彩內(nèi)容