SpringSeurity的授权和认证

package springseurity.seurity.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 SeurityConfig extends WebSecurityConfigurerAdapter {
    /*
    * 授权
    * */
    //链式编程
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所有人可访问   功能页有权限的人才能访问
        //请求授权的规则
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/lever1/**").hasRole("vip1")
                .antMatchers("/lever2/**").hasRole("vip2")
                .antMatchers("/lever3/**").hasRole("vip3");
        //没有权限默认回到登录页,开启登录页面
        //http.formLogin()默认有官方登录页
        //http.formLogin().loginPage("/toLogin");  定制自己的登录页
        http.formLogin()/*.loginPage("/toLogin").usernameParameter("user").passwordParameter("pwd").loginProcessingUrl("/login")*/;
        //开启注销
        http.logout().logoutSuccessUrl("/");
        //防止网站攻击工具  get post
        http.csrf().disable();//关闭csrf功能
        //开启记住我功能
        http.rememberMe().rememberMeParameter("rememberMe");/*默认保存两周*/
    }
    /*
    * 认证
    * */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //new BCryptPasswordEncoder() 对密码进行加密
        //new BCryptPasswordEncoder().encode() 对密码进行编码
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
        .withUser("zyp").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip3")
        .and()
        .withUser("cpj").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2")
        .and()
        .withUser("mjx").password(new BCryptPasswordEncoder().encode("123456")).roles("vip3")
        .and()
        .withUser("drn").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
``
}

posted @ 2020-11-22 14:52  花红  阅读(74)  评论(0)    收藏  举报