SpringBoot集成Security(二)----实现简单登陆

SpringBoot集成Security(二)----实现简单登陆

上篇文章已经搭建好了项目,那么现在就让我们来看看一些自定义配置吧。
创建一个WebSecurityConfig类继承于WebSecurityConfigurerAdapter,然后我们可以复写它的方法。
注意要添加@Configuration和@EnableWebSecurity注解
为什么要添加EnableWebSecurity注解?

HttpSecurity自定义配置(配置拦截路径和角色)

	@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/**")
                .hasRole("admin")
                .antMatchers("/user/**")
                .hasAnyRole("ADMIN", "USER")
                .antMatchers("/superadmin/**")
                .access("hasRole('ADMIN') and hasRole('MANAGER')")
                .anyRequest().authenticated()
                .and()
                .formLogin() /*表单登陆相关配置*/
                .loginPage() //自定义登陆界面
                .loginProcessingUrl("/login") //登陆请求处理接口
                .usernameParameter("name")  //登陆接口传参用户名参数名
                .passwordParameter("password")  //登陆接口传参密码参数名
                .successForwardUrl()  //登陆成功跳转Url
                .successHandler() //自定义登陆成功处理逻辑
                .failureForwardUrl("/login")  //登陆失败跳转Url
                .failureHandler() //自定义登陆失败处理逻辑
                .permitAll()  //登陆处理的Url不进行拦截
                .and()
                .logout() //注销配置
                .logoutUrl()  //注销请求Url
                .clearAuthentication(true) //是否清除身份信息
                .invalidateHttpSession(true) //是否失效session
                .addLogoutHandler()  //添加自定义注销处理逻辑
                .logoutSuccessUrl() //注销成功跳转Url
                .logoutSuccessHandler() //注销成功处理逻辑
                .permitAll()  //注销Url放行
                .rememberMe()  //使用rememberMe功能
                .and()
                .csrf().disable();
    }

WebSecurity自定义配置 (放行静态资源)

复写该方法用来放行一些不需要进行拦截的资源

	@Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
                .antMatchers("/static/**", "/swagger2/**");
    }

基于内存的配置

inMemoryAuthentication()标明我们将使用内存的方法,后续用.withUser()进行用户名配置,用.password()进行密码配置,.roles()进行角色配置,多用户用.and()进行连接,.accountExpired()可以设置账户是否过期,.accountLocked()设置账户是否被锁定。

	@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin")
                .password("123456")
                .roles("ADMIN", "USER")
                .and()
                .withUser("user")
                .password("12321")
                .roles("USER")
                .accountExpired(false)
                .accountLocked(false);
    }

注意:如果使用了密码加密相应的需要更改密码为:
.password(passwordEncoder().encode(“123456”))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值