天天看点

SpringSecurity(安全框架)用户认证和授权

以下为源码部分,通过源码学习

@EnableWebSecurity 
     public class FormLoginSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
     protected void configure(HttpSecurity http) throws Exception {
           http.authorizeRequests().antMatchers("/**").hasRole("USER").and().formLogin()
     *              .usernameParameter("username") // default is username
     *              .passwordParameter("password") // default is password
     *              .loginPage("/authentication/login") // default is /login with an HTTP get
     *              .failureUrl("/authentication/login?failed") // default is /login?error
     *              .loginProcessingUrl("/authentication/login/process"); // default is /login
     *                                                                      // with an HTTP
     *                                                                      // post
        }

     @Override
      protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
    }
}      

1.权限(为某些文件设置权限)

//链式编程
    //授权
    @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页面
        http.formLogin()
                .usernameParameter("username")
                .passwordParameter("password")
                .loginPage("/toLogin")
                .loginProcessingUrl("/login");

        //注销,开启了注销功能,跳到首页
        http.logout().logoutSuccessUrl("/");

        // 防止网站工具:get,post
        http.csrf().disable();//关闭csrf功能,登录失败肯定存在的原因

        //开启记住我功能: cookie,默认保存两周,自定义接收前端的参数
        http.rememberMe().rememberMeParameter("remember");


    }      

所设置页面均不可访问,需要通过用户认证并且登录后即可访问

2.认证(认证的用户才有资格登录系统)

// 认证,springboot 2.1.x 可以直接使用,用户认证,认证后的用户可以登录系统
    // 密码编码: PasswordEncoder    加密     new BCryptPasswordEncoder()即为设置加密
    // 在spring Secutiry 5.0+ 新增了很多加密方法
    //    and()作为连接使用
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //这些数据正常应该中数据库中读
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("whx").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");
    }      

通过用户认证确定什么用户可以访问什么页面

首先让配置文件继承 WebSecurityConfigurerAdapter,然后通过@@EnableWebSecurity 开启WebSecurity模式。然后通过自动构造方法找到所需方法。

完整配置文件如下:

package nuc.ss.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;

// AOP:拦截器
@EnableWebSecurity  // 开启WebSecurity模式
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页面
        http.formLogin()
                .usernameParameter("username")
                .passwordParameter("password")
                .loginPage("/toLogin")
                .loginProcessingUrl("/login");

        //注销,开启了注销功能,跳到首页
        http.logout().logoutSuccessUrl("/");

        // 防止网站工具:get,post
        http.csrf().disable();//关闭csrf功能,登录失败肯定存在的原因

        //开启记住我功能: cookie,默认保存两周,自定义接收前端的参数
        http.rememberMe().rememberMeParameter("remember");


    }




    // 认证,springboot 2.1.x 可以直接使用,用户认证,认证后的用户可以登录系统
    // 密码编码: PasswordEncoder    加密     new BCryptPasswordEncoder()即为设置加密
    // 在spring Secutiry 5.0+ 新增了很多加密方法
    //    and()作为连接使用
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //这些数据正常应该中数据库中读
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("whx").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");
    }


}      

用户认证如果需要从数据库中取数据的话则将用户认证的代码通过数据库的方式写入;