使用spring secuity自定義登錄

我們先看spring secuity的默認登錄頁面,

  • 加入springmvc,spring secuityservlet的一些依賴,配置jetty的插件,配置端口是8001,contextPath是"/"
<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.13.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>4.2.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>4.2.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>


    <build>
        <finalName>secuity-quickstart-config</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.4.3.v20170317</version>
                <configuration>
                    <httpConnector>
                        <port>8001</port>
                    </httpConnector>
                    <webApp>
                        <contextPath>/</contextPath>
                    </webApp>
                </configuration>
            </plugin>
        </plugins>
    </build>
  • 定義系統(tǒng)啟動類
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    //系統(tǒng)啟動的時候的根類
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[]{WebAppConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }

    //設(shè)置成/*表示攔截靜態(tài)的文件
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

}
  • web入口類
/**
 *
 * 入口類,啟動spring mvc,啟動spring secuity
 */
@EnableWebMvc
@EnableWebSecurity
@ComponentScan("com.zhihao.miao.secuity")
public class WebAppConfig extends WebMvcConfigurerAdapter {
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}
  • spring security配置類
/**
 *
 * 初始化spring security
 */
public class WebAppSecurityInitializer extends AbstractSecurityWebApplicationInitializer {

    protected String getDispatcherWebApplicationContextSuffix() {
        return AbstractDispatcherServletInitializer.DEFAULT_SERVLET_NAME;
    }
}
  • 具體的controller
@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello(){
        return "hello spring secuity";
    }

    @GetMapping("/home")
    public String home(){
        return "home spring security";
    }

    @GetMapping("/admin")
    public String admin(){
        return "admin spring secuity";
    }
}
  • 權(quán)限用戶名密碼的具體配置
Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("GUEST");
        auth.inMemoryAuthentication().withUser("zhihao.miao").password("123456").roles("USER");
        auth.inMemoryAuthentication().withUser("lisi").password("12345678").roles("USER", "ADMIN");
    }

    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/hello").hasRole("GUEST");
        http.authorizeRequests().antMatchers("/home").hasRole("USER");
        http.authorizeRequests().antMatchers("/admin").hasRole("ADMIN");


        http.authorizeRequests().antMatchers("/**/*.html").permitAll();
        http.authorizeRequests().antMatchers("/**/*.css").permitAll();
        http.authorizeRequests().antMatchers("/**/*.js").permitAll();
        http.authorizeRequests().antMatchers("/**/*.png").access("permitAll");

        http.authorizeRequests().anyRequest().authenticated();

        //httpbasee認證
        http.httpBasic();
    }
}
  • 默認的登錄頁面


    httpbasic認證

http.formLogin();是spring secuity默認的登錄頁面。

自定義登錄

  • 先定義一個登錄頁面,將其頁面放在了WEB-INF下面的jsp目錄下,然后需要在啟動類上加入視圖解析器
@EnableWebMvc
@EnableWebSecurity
@ComponentScan("com.zhihao.miao.secuity")
public class WebAppConfig extends WebMvcConfigurerAdapter {
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

     //配置視圖解析器
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp();
    }
}
  • Controller中定義一個url跳轉(zhuǎn)到該登錄頁面

根據(jù)上面的視圖解析器,我們就知道登錄的跳轉(zhuǎn)頁面的路徑是/WEB-INF/jsp/login.jsp

@Controller
public class LoginController {

    @GetMapping("/sys/login")
    public String login(){
        return "/jsp/login";
    }
}
  • spring security中配置

登錄的跳轉(zhuǎn)頁面,和登錄的動作url不去做權(quán)限認證。

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("GUEST");
        auth.inMemoryAuthentication().withUser("zhihao.miao").password("123456").roles("USER");
        auth.inMemoryAuthentication().withUser("lisi").password("12345678").roles("USER", "ADMIN");
    }

    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/hello").hasRole("GUEST");
        http.authorizeRequests().antMatchers("/home").hasRole("USER");
        http.authorizeRequests().antMatchers("/admin").hasRole("ADMIN");

        //登錄的跳轉(zhuǎn)頁面,和登錄的動作url不應(yīng)該有權(quán)限認證。
        http.authorizeRequests().antMatchers("/sys/login").permitAll();
        http.authorizeRequests().antMatchers("/**/*.html").permitAll();
        http.authorizeRequests().antMatchers("/**/*.css").permitAll();
        http.authorizeRequests().antMatchers("/**/*.js").permitAll();
        http.authorizeRequests().antMatchers("/**/*.png").access("permitAll");

        http.authorizeRequests().anyRequest().authenticated();

        http.formLogin().
                //登錄的時候跳轉(zhuǎn)的登錄頁面url
                loginPage("/sys/login").
               //登錄頁面提交時候的請求
                loginProcessingUrl("/doLogin").
                defaultSuccessUrl("/public/login/ok.html"). //如果直接訪問登錄頁面,則登錄成功后重定向到這個頁面,否則跳轉(zhuǎn)到之前想要訪問的頁面
                permitAll(); //就是設(shè)置loginProcessingUrl()也不需要權(quán)限認證
    }
}
  • 登錄頁面:

詳細的登錄頁面可以查看文章的最后的項目鏈接

<div class="login">
    <h1>Login</h1>
    <form method="post" action="/doLogin">
        <input type="hidden" name="${ _csrf.parameterName}" value="${ _csrf.token}" />
        <input type="text" name="username" placeholder="用戶名" />
        <input type="password" name="password" placeholder="密碼"/>
        <button type="submit" class="btn btn-primary btn-block btn-large">登錄</button>
    </form>
</div>
  • 測試
    訪問localhost:8001/hello,跳轉(zhuǎn)到http://localhost:8001/sys/login頁面,具體頁面如下:
  • 一些更加細節(jié)的定制登錄的api使用

比如說失敗重定向(可以在重定向方法中獲取到失敗的異常),失敗跳轉(zhuǎn),成功登錄之后重定向等等api的使用

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //賬號被鎖
        auth.inMemoryAuthentication().withUser("zhangsan").password("123456").accountLocked(true).roles("GUEST");
        //賬號過期
        auth.inMemoryAuthentication().withUser("zhihao.miao").password("123456").accountExpired(true).roles("USER");
        auth.inMemoryAuthentication().withUser("lisi").password("12345678").roles("USER", "ADMIN");
    }

    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/hello").hasRole("GUEST");
        http.authorizeRequests().antMatchers("/home").hasRole("USER");
        http.authorizeRequests().antMatchers("/admin").hasRole("ADMIN");

        //登錄的跳轉(zhuǎn)頁面,和登錄的動作url不應(yīng)該有權(quán)限認證。
        http.authorizeRequests().antMatchers("/sys/login").permitAll();
        http.authorizeRequests().antMatchers("/**/*.html").permitAll();
        http.authorizeRequests().antMatchers("/**/*.css").permitAll();
        http.authorizeRequests().antMatchers("/**/*.js").permitAll();
        http.authorizeRequests().antMatchers("/**/*.png").access("permitAll");

        http.authorizeRequests().anyRequest().authenticated();

        http.formLogin().
                loginPage("/sys/login").
                loginProcessingUrl("/doLogin").
                failureForwardUrl("/sys/loginFail").   //使用forward的方式,能拿到具體失敗的原因,并且會將錯誤信息以SPRING_SECURITY_LAST_EXCEPTION的key的形式將AuthenticationException對象保存到request域中
                        //failureUrl("/public/login/fail.html").   //失敗重定向,拿不到具體失敗的原因
                defaultSuccessUrl("/public/login/ok.html"). //如果直接訪問登錄頁面,則登錄成功后重定向到這個頁面,否則跳轉(zhuǎn)到之前想要訪問的頁面
                //defaultSuccessUrl("/public/login/ok.html",true). //登錄成功后,都直接重定向到這個頁面
                        permitAll();
    }
}

比如說重定向拿不到登錄失敗的異常,而failureForwardUrl()的api卻可以,點入failureForwardUrl源碼查看,FormLoginConfigurer的文檔說明,如果登錄失敗會拋出
SPRING_SECURITY_LAST_EXCEPTION異常,取到消息可以使用${SPRING_SECURITY_LAST_EXCEPTION.message}

可以在Controller層中通過HttpServletRequest拿到登錄失敗的異常,

    @PostMapping("/sys/loginFail")
    public String fail(HttpServletRequest req){
        AuthenticationException exp = (AuthenticationException)req.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
        System.out.println("exp:"+exp.getMessage());
        if(exp instanceof BadCredentialsException){
            //將錯誤信息放到request域中
            req.setAttribute("error_msg", "用戶名或密碼錯誤");
        } else if(exp instanceof AccountExpiredException){
            req.setAttribute("error_msg", "賬戶過期");
        } else if(exp instanceof LockedException){
            req.setAttribute("error_msg", "賬戶已被鎖");
        }else{
            //其他錯誤打印這些信息
            System.out.println(exp.getMessage());
        }
        return "/jsp/login";
    }

登錄頁面打印失敗的異常

<div class="login">
    <h1>Login</h1>
    <form method="post" action="/doLogin">
        <input type="hidden" name="${ _csrf.parameterName}" value="${ _csrf.token}" />
        <input type="text" name="username" placeholder="用戶名" />
        <input type="password" name="password" placeholder="密碼"/>
        <button type="submit" class="btn btn-primary btn-block btn-large">登錄</button>
    </form>
    <div class="login-bottom" style="color:red;">${SPRING_SECURITY_LAST_EXCEPTION.message}</div>
</div>

此時就可以把錯誤信息打印到頁面上

  • 還可以自定義登錄成功和失敗的handler進行權(quán)限驗證,自己根據(jù)自己的業(yè)務(wù)代碼來進行定制
    通過successHandlerfailureHandler方法來定義
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("GUEST");
        auth.inMemoryAuthentication().withUser("zhihao.miao").password("123456").roles("USER");
        auth.inMemoryAuthentication().withUser("lisi").password("12345678").roles("USER", "ADMIN");
    }

    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/hello").hasRole("GUEST");
        http.authorizeRequests().antMatchers("/home").hasRole("USER");
        http.authorizeRequests().antMatchers("/admin").hasRole("ADMIN");

        //登錄的跳轉(zhuǎn)頁面,和登錄的動作url不應(yīng)該有權(quán)限認證。
        http.authorizeRequests().antMatchers("/sys/login").permitAll();
        http.authorizeRequests().antMatchers("/**/*.html").permitAll();
        http.authorizeRequests().antMatchers("/**/*.css").permitAll();
        http.authorizeRequests().antMatchers("/**/*.js").permitAll();
        http.authorizeRequests().antMatchers("/**/*.png").access("permitAll");

        http.authorizeRequests().anyRequest().authenticated();

        http.formLogin().
                loginPage("/sys/login").
                loginProcessingUrl("/doLogin").
                successHandler((request, response, authentication) -> {
                    //登錄成功的時候跳轉(zhuǎn)到/public/login/ok.html
                    System.out.println("========登陸成功=======" + authentication.getName());
                    response.sendRedirect("/public/login/ok.html");
                }).failureHandler((request, response, exception) -> {
                    //登錄失敗的時候跳轉(zhuǎn)到/public/login/fail.html
                    System.out.println("=======登陸失敗=======" + exception.getMessage());
                    response.sendRedirect("/public/login/fail.html");
                }).permitAll();
    }
}

參考代碼

secuity-config-login

參考資料

官方文檔
Spring Security 從入門到進階系列教程

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,224評論 6 529
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 97,916評論 3 413
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,014評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,466評論 1 308
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,245評論 6 405
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 54,795評論 1 320
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,869評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,010評論 0 285
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,524評論 1 331
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 40,487評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,634評論 1 366
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,173評論 5 355
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 43,884評論 3 345
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,282評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,541評論 1 281
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,236評論 3 388
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,623評論 2 370

推薦閱讀更多精彩內(nèi)容