正在加载中,请稍后

SpringSecurity

Springboot+SpringSecurity

SpringSecurity是一个基于Spring的提供声明式的安全框架,它提供了一组可以在Spring应用上下文中配置的Bean,充分利用Spring IOC、DI、AOP功能,为应用提供安全访问控制,减少为安全控制而编写的大量重复代码。

SpringSecurity两大功能核心

认证Authentication

授权Authorization

Security流程:

1.当用户登录时,前端把用户名和密码传入后端,后端用一个Token类来封装登录信息

2把Token里的用户名和密码与数据库的用户名密码做比对,成功就登录成功,将用户信息放入SecurityContextHolder中,(上下文容器,类似session)。

3.在用户访问一个资源时,要判断用户是否已登录,然后判断权限是否充分。

配置类

@Configuration      // 声明为配置类
@EnableWebSecurity      // 启用 Spring Security web 安全的功能
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?error 重定向到这里表示登录失败
        http.formLogin()
            .usernameParameter("username")
            .passwordParameter("password")
            .loginPage("/toLogin")
            .loginProcessingUrl("/login"); // 登陆表单提交请求
 
        //开启自动配置的注销的功能
            // /logout 注销请求
            // .logoutSuccessUrl("/"); 注销成功来到首页
 
        http.csrf().disable();//关闭csrf功能:跨站请求伪造,默认只能通过post方式提交logout请求
        http.logout().logoutSuccessUrl("/");
 
        //记住我
        http.rememberMe().rememberMeParameter("remember");
    }
 
    //定义认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //在内存中定义,也可以在jdbc中去拿....
        //Spring security 5.0中新增了多种加密方式,也改变了密码的格式。
        //要想我们的项目还能够正常登陆,需要修改一下configure中的代码。我们要将前端传过来的密码进行某种方式加密
        //spring security 官方推荐的是使用bcrypt加密方式。
 
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("kuangshen").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","vip2");
    }
}
posted @ 2021-05-17 09:31  wode虎纹猫  阅读(95)  评论(0)    收藏  举报
Live2D