天天看點

SpringSecurity的使用

Spring Security 是針對Spring項目的安全架構,也是Spring Boot底層安全模
塊預設的技術選型,他可以實作強大的Web安全控制,對于安全控制,我們僅需要
引入 spring-boot-starter-security 子產品,進行少量的配置,即可實作強大的
安全管理!
           
使用步驟:
1:加入依賴
	<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
2:編寫配置類        
           
package com.dongmu.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;


@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");



        http.formLogin().loginPage("/toLogin");

        http.csrf().disable();
        http.logout().logoutSuccessUrl("/toLogin");

        http.rememberMe().rememberMeParameter("remember");



    }

    /*認證*/

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("dongmu").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }

}

           

更多詳情:https://blog.csdn.net/Sgxlebron/article/details/122757103