1. 程式人生 > 實用技巧 >使用springSecurity實現登入認證和授權

使用springSecurity實現登入認證和授權

1.引入依賴

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

2.編寫相應的配置類

//開啟Spring Security
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    
//認證,劃分不同的角色 protected void configure(HttpSecurity http) throws Exception { //首頁所有人可以訪問 http.authorizeRequests() .antMatchers("/").permitAll() .antMatchers("/level1/**").hasRole("vip1") .antMatchers("/level2/**").hasRole("vip2") .antMatchers(
"/level3/**").hasRole("vip3"); //沒登陸前點需要許可權的頁面,會跳轉至登陸頁面 //loginPage為自定義頁面,loginProcessUrl為驗證使用者密碼的路徑 http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login"); http.csrf().disable(); //開啟登出,登出成功跳轉相應的頁面 http.logout().logoutSuccessUrl("/"); //開啟記住我 http.rememberMe().rememberMeParameter("remember"); } @Override
//授權,賦予使用者角色 protected void configure(AuthenticationManagerBuilder auth) throws Exception { //基於記憶體,授權 auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("yzy").password(new BCryptPasswordEncoder().encode("123456")) .roles("vip1"); } }