1. 程式人生 > 其它 >springboot-springsecurity:記住我和登入頁定製

springboot-springsecurity:記住我和登入頁定製

承接:springboot-springsecuroty:登出和許可權控制

1 記住我實現

1.1 在SecurityConfig中新增http.rememberMe();這行程式碼

src/main/java/com/lv/config/SecurityConfig.java

package com.lv.config;

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.crypto.bcrypt.BCryptPasswordEncoder;

//AOP : 攔截器!
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //授權
    @Override
    public void configure(HttpSecurity http) throws Exception {
        //首頁所有人都可以訪問,功能頁只有對應的有許可權的人才能訪問
        //請求授權的規則~(鏈式程式設計)
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //沒有許可權預設會跳轉到登入頁,需要開啟登入頁面
        http.formLogin();

        //登出,開啟了登出功能,跳到首頁
        http.logout().logoutSuccessUrl("/");

        //防止跨站工具, get,post
        http.csrf().disable();//關閉csrf功能,登出失敗可能的原因

        //開啟記住我功能 cookie,預設儲存兩週
        http.rememberMe();
    }
    //認證,springboot 2.1.x 可以直接使用
    //密碼編碼:PasswordEncoder
    //在Spring Security 5.0+ 新增了很多加密方法~
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //這些資料正常應該從資料庫中讀
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("lv").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
}

1.2 啟動程式測試

訪問登入頁面,會出現一個renmember me 的單選框

選中renmember me 的單選框點選登入

跳轉到首頁,並在cookies中存入賬戶資訊,這個賬戶儲存有效期是兩週,此時即便重啟瀏覽器,賬戶資訊也依舊存在

2 登入頁定製

2.1 在SecurityConfig加入登入頁的配置,和remem me的配置

src/main/java/com/lv/config/SecurityConfig.java

package com.lv.config;

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.crypto.bcrypt.BCryptPasswordEncoder;

//AOP : 攔截器!
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //授權
    @Override
    public void configure(HttpSecurity http) throws Exception {
        //首頁所有人都可以訪問,功能頁只有對應的有許可權的人才能訪問
        //請求授權的規則~(鏈式程式設計)
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //沒有許可權預設會跳轉到登入頁,需要開啟登入頁面
        http.formLogin()
                .loginPage("/toLogin")//登入頁
                .usernameParameter("user")//賬號
                .passwordParameter("pwd")//密碼
                .loginProcessingUrl("/login");//登入請求地址

        //登出,開啟了登出功能,跳到首頁
        http.logout().logoutSuccessUrl("/");

        //防止跨站工具, get,post
        http.csrf().disable();//關閉csrf功能,登出失敗可能的原因

        //開啟記住我功能 cookie,預設儲存兩週,自定義接收前端的引數
        http.rememberMe().rememberMeParameter("remember");
    }
    //認證,springboot 2.1.x 可以直接使用
    //密碼編碼:PasswordEncoder
    //在Spring Security 5.0+ 新增了很多加密方法~
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //這些資料正常應該從資料庫中讀
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("lv").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
}

2.2 修改index.html的form表單

一共修改了三個部分:

  • 修改form表單的提交地址
  • 修改使用者名稱和密碼的引數名
  • 添加了一個記住我的多選框

src/main/resources/templates/views/login.html

<form th:action="@{/login}" method="post">
    <div class="field">
        <label>Username</label>
        <div class="ui left icon input">
            <input type="text" placeholder="Username" name="user">
            <i class="user icon"></i>
        </div>
    </div>
    <div class="field">
        <label>Password</label>
        <div class="ui left icon input">
            <input type="password" name="pwd">
            <i class="lock icon"></i>
        </div>
    </div>
    <input type="checkbox" name="remember"> 記住我
    <input type="submit" class="ui blue submit button"/>
</form>

2.3 重啟程式測試

點選登入會跳到我們自定義的登入頁上了

點選提交後成功登入,並且賬戶資訊依舊可以存入cookies

登入頁定製成功實現