spring-security学习之(一)出入安全框架

今天使用的是spring-security搭建的安全框架。

使用的是springboot

首先引入spring-security的依赖是:

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

安全框架最重要的两点就是认证和授权:

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

        //没有权限,跳转到登录页面,需要进行开启
        // login
        //定制login页面
        http.formLogin().loginPage("/toLogin").usernameParameter("user").passwordParameter("pwd").loginProcessingUrl("/login");

        //开启注销功能
        http.logout();

        //关闭csrf功能
        http.csrf().disable();

        //记住我功能,保存的是cookie,默认保存两个礼拜
        http.rememberMe().rememberMeParameter("remember");
    }

    //认证
    //有多种加密方式
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("kuanshen").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2", "vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2", "vip3", "vip1")
                .and()
                .withUser("geest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }

}

以上这些方面就可以简单的搭建一个小的项目。用来完成认证和授权。

但是里面还有很多的细节,需要自己慢慢的体会。

今天只做一个简单的配置用来体验一下安全框架

原文地址:https://www.cnblogs.com/qingmuchuanqi48/p/12694741.html