Spring Security:一、入门(新)

项目结构:

 代码下载:555555

一、创建项目

        1.1、创建springboot

        1.2、导包

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

        1.3、创建controller        

@RestController
public class HelloController {

    /**
     * 不需要登录
     * @return
     */
    @GetMapping("/noLogin")
    public String noLogin(){
        return "no login";
    }

}

        1.4、启动项目

        1.5、访问 ​http://localhost:8080/noLogin​ ,页面自动跳转到登录页面,

                

                        输入默认用户名:user

                        随机密码:

                

         1.6、访问成功

                

 二、自定义用户名和密码

         1、配置文件

                在 application.properties 文件中配置信息:              

spring.security.user.name=admin
spring.security.user.password=admin

        2、代码中配置(先注释配置文件)

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    //通过重写configure方法,进行创建用户。表示在内存中配置了两个用户
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.inMemoryAuthentication()
                .withUser("admin1")
                .password(passwordEncoder().encode("admin1"))
                .roles("admin1");

        auth.inMemoryAuthentication()
                .withUser("user1")
                .password(passwordEncoder().encode("user1"))
                .roles("user1");

    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

        注:从 Spring5 开始,强制要求密码要加密,如果非不想加密,可以使用一个过期的 PasswordEncoder 的实例 NoOpPasswordEncoder,这里配置的内存都是放在内存中的

        

三、忽略拦截

        3.1、在 WebSecurityConfig 类中添加以下代码

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/noLogin"); // 需要忽略的路径(多个用逗号隔开,或者或者不重要)
    }

四、登录权限配置

        对于登录成功、登录失败,我们都可以继承WebSecurityConfigurerAdapter类来进行配置

        4.1、修改controller,新增方法和注解@PreAuthorize

@RestController
public class HelloController {

    /**
     * 不需要登录
     * @return
     */
    @GetMapping("/noLogin")
    public String noLogin(){
        return "No login";
    }

    /**
     * 需要登录,不需要任何权限
     * @return
     */
    @GetMapping("/haveLogin")
    public String haveLogin(){
        return "Have login";
    }

    /**
     * 需要登录,需要adminRole权限
     * @return
     */
    @GetMapping("/admin/role")
    @PreAuthorize("hasAnyRole('adminRole')")
    public String helloAdmin(){
        return "hello adminRole";
    }

    /**
     * 需要登录,需要textRole权限
     * @return
     */
    @GetMapping("/test/role")
    @PreAuthorize("hasAnyRole('testRole')")
    public String helloUser(){
        return "hello testRole";
    }

    /**
     * 需要登录,需要adminRole和textRole权限
     * @return
     */
    @GetMapping("/role/adminAndTest")
    @PreAuthorize("hasAnyRole('adminRole', 'testRole')")
    public String index(){
        return "adminRoleAndTestRole";
    }

}

        4.2、继续改造 WebSecurityConfig 类,添加以下代码

    /**
     * 配置权限拦截机制
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //参数文档说明:https://blog.csdn.net/weixin_34346099/article/details/92479543
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/admin/**").hasRole("adminRole") // 访问/admin的url需要拥有adminRole权限
                .antMatchers("/test/**").hasRole("testRole") // 访问/test的url需要拥有testRole权限
                .anyRequest().authenticated()//剩余的其他接口,登录之后就能访问
                //.anyRequest().permitAll()//除了以上配置,其它的url都可以访问
                .and()
                .formLogin()//允许表单登录(没有定义登录页面,默认使用security的登录也)

                //自定义登录页面
                /*.loginPage("/login-view")// 登录页面:没有设置loginPage(),那么默认的登录页面就是"/login"
                .loginProcessingUrl("/login") // 登录表单提交请求
                .successForwardUrl("/login-success")//自定义登录成功的页面地址

                //自定义登出
                .and()
                .logout() //登出
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login-view?logout")*/
        ;

    }

到这里Spring Security入门结束了 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值