使用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");
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM