SpringSecurity

suaxi
2020-12-26 / 0 评论 / 310 阅读 / 正在检测是否收录...

SpringSecurity

1、导入依赖

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

2、Config配置

package com.sw.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;

/**
 * @Author suaxi
 * @Date 2020/12/24 14:45
 */

@EnableWebSecurity
public class SercurityConfig 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");

        //没有权限,默认跳转到登录页
        //自定义登录页
        http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login");
        http.csrf().disable();

        //注销
        http.logout().logoutSuccessUrl("/");

        //开启记住我
        //自定义rememberMe
        http.rememberMe().rememberMeParameter("remember");
    }

    //认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //在内存中虚拟用户
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("1").password(new BCryptPasswordEncoder().encode("1")).roles("vip1")
                .and()
                .withUser("2").password(new BCryptPasswordEncoder().encode("1")).roles("vip2")
                .and()
                .withUser("3").password(new BCryptPasswordEncoder().encode("1")).roles("vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("1")).roles("vip1","vip2","vip3");


    }
}
0

评论 (0)

取消