springSecurity基本使用2(实现简单的登录功能)


前言


1、不使用数据库,实现一个简单的登录功能,只有在登录后才能访问我们的接口
2、springSecurity提供了一种基于内存的验证方法(使用自己定义的用户,不使用默认的)


一、实现用户创建,登陆后才能访问接口(注重用户认证)

1.定义一个内存用户,不使用默认用户

重写configure(AuthenticationManagerBuilder auth)方法,实现在内存中定义一个 (用户名/密码/权限:admin/123456/admin) 的用户

package com.example.springsecurity;

import org.springframework.context.annotation.Configuration;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.stereotype.Component;

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //基于内存的验证方法
        auth.inMemoryAuthentication().withUser("admin").password("123456").roles("admin");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {             //批处理静态资源,都不拦截处理
        web.ignoring().mvcMatchers("/js/**","/css/**","/images/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {       // 这是一个重要的方法,这个方法决定了我们哪些请求会被拦截以及一些请求该怎么处理
        http.authorizeRequests()  //安全过滤策略
                .antMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and() //and添加允许别的操作
                .logout().permitAll() //允许支持注销,支持随意访问
                .and()
                .formLogin();   //允许表单登录
        http.csrf().disable();  //关闭csrf认证
    }
}

2.效果

根目录可以直接通过验证,其他接口需要经过springSecurity,输入admin 123456后登陆系统
在这里插入图片描述
在这里插入图片描述

3.退出登陆

地址栏输入:http://localhost:8080/login?logout,执行退出登陆
在这里插入图片描述

4.再创建一个张三用户,同时支持多用户登陆

package com.example.springsecurity;

import org.springframework.context.annotation.Configuration;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.stereotype.Component;

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //基于内存的验证方法
        auth.inMemoryAuthentication().withUser("admin").password("123456").roles("admin");
        auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("admin");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {             //批处理静态资源,都不拦截处理
        web.ignoring().mvcMatchers("/js/**","/css/**","/images/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {       // 这是一个重要的方法,这个方法决定了我们哪些请求会被拦截以及一些请求该怎么处理
        http.authorizeRequests()  //安全过滤策略
                .antMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and() //and添加允许别的操作
                .logout().permitAll() //允许支持注销,支持随意访问
                .and()
                .formLogin();   //允许表单登录
        http.csrf().disable();  //关闭csrf认证
    }
}

二、实现管理员功能(注重权限控制)

实现角色功能,不同角色拥有不同功能:管理员拥有管理功能,而普通组员只能拥有最普通的功能

1.创建一个普通用户demo

auth.inMemoryAuthentication().withUser("demo").password("demo").roles("user");

创建demo用户,角色为demo,详细代码如下

package com.example.springsecurity;

import org.springframework.context.annotation.Configuration;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.stereotype.Component;

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //基于内存的验证方法
        auth.inMemoryAuthentication().withUser("admin").password("123456").roles("admin");
        auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("admin");
        auth.inMemoryAuthentication().withUser("demo").password("demo").roles("user");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {             //批处理静态资源,都不拦截处理
        web.ignoring().mvcMatchers("/js/**","/css/**","/images/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {       // 这是一个重要的方法,这个方法决定了我们哪些请求会被拦截以及一些请求该怎么处理
        http.authorizeRequests()  //安全过滤策略
                .antMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and() //and添加允许别的操作
                .logout().permitAll() //允许支持注销,支持随意访问
                .and()
                .formLogin();   //允许表单登录
        http.csrf().disable();  //关闭csrf认证
    }
}

2.创建/roleAuth接口

此接口只能admin角色才能登陆
1、@EnableGlobalMethodSecurity注解使role验证注解生效
2、@PreAuthorize(“hasRole(‘ROLE_admin’)”)注解声明哪个角色能访问此接口

package com.example.springsecurity;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
@EnableGlobalMethodSecurity(prePostEnabled = true)  //必须加这行,不然role验证无效
public class SpringsecurityApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringsecurityApplication.class, args);
    }

    @RequestMapping("/")
    public String home(){
        return "hello spring boot";
    }

    @RequestMapping("/hello")
    public String hello(){
        return "hello word";
    }

    @PreAuthorize("hasRole('ROLE_admin')")  //当我们期望这个方法经过role验证的时候,需要加这个注解;ROLE必须大写
    @RequestMapping("/roleAuth")
    public String role(){
        return "admin  Auth";
    }

}

3.效果

demo用户登陆成功可以访问/接口,但是不能访问/roleAuth接口
在这里插入图片描述
在这里插入图片描述
admin管理员既能访问/接口,也能访问/roleAuth接口
在这里插入图片描述

三、实现数据库管理用户(注重数据库认证用户)

1.我们需要把之前创建的admin zhangsan demo三个用户放到数据库中 2.我们需要使用MyUserService来管理这些用户

1.创建一个MyUserService类

1.此类实现UserDetailsService(这边不真实查询数据库)
package com.example.springsecurity;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Component
public class MyUserService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        return null;//数据库操作逻辑
    }
}

2.密码自定义验证类

1.此类实现自定义密码验证
package com.example.springsecurity;

import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

public class MyPasswdEncoder implements PasswordEncoder {
    private final static String SALT = "123456";
    @Override
    public String encode(CharSequence rawPassword) {
        //加密:堆原始的密码进行加密,这边使用md5进行加密
        Md5PasswordEncoder encoder = new Md5PasswordEncoder();
        return encoder.encodePassword(rawPassword.toString(), SALT);
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        //拿原始的密码和加密后的密码进行匹配
        Md5PasswordEncoder encoder = new Md5PasswordEncoder();
        return encoder.isPasswordValid(encodedPassword,rawPassword.toString(),SALT);
    }
}

3.自定义数据库查询&默认数据库查询、自定义密码验证配置

1.支持自定义数据库查询 2.支持默认数据库查询(数据库结构必须和默认的一致) 两者选择其中一个
package com.example.springsecurity;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.stereotype.Component;

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    MyUserService myUserService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //基于内存的验证方法
//        auth.inMemoryAuthentication().withUser("admin").password("123456").roles("admin");
//        auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("admin");
//        auth.inMemoryAuthentication().withUser("demo").password("demo").roles("user");


        //1、自己实现数据库的查询,指定我们要使用的UserService和自定义的密码验证器
        auth.userDetailsService(myUserService).passwordEncoder(new MyPasswdEncoder());
        //2、sprinSecurity在数据库管理方面支持一套默认的处理,可以指定根据用户查询,权限查询,这情况下用户表必须和默认的表结构相同,具体查看user.ddl文件

        auth.jdbcAuthentication().usersByUsernameQuery("").authoritiesByUsernameQuery("").passwordEncoder(new MyPasswdEncoder());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {             //批处理静态资源,都不拦截处理
        web.ignoring().mvcMatchers("/js/**","/css/**","/images/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {       // 这是一个重要的方法,这个方法决定了我们哪些请求会被拦截以及一些请求该怎么处理
        http.authorizeRequests()  //安全过滤策略
                .antMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and() //and添加允许别的操作
                .logout().permitAll() //允许支持注销,支持随意访问
                .and()
                .formLogin();   //允许表单登录
        http.csrf().disable();  //关闭csrf认证
    }
}

四、sprinSecurity支持的4种使用表达式的权限注解

1.支持的4种注解


    @PreAuthorize("hasRole('ROLE_admin')")  //1.方法调用前:当我们期望这个方法经过role验证的时候,需要加这个注解;ROLE必须大写
    @PostAuthorize("hasRole('ROLE_admin')")//2.方法调用后
    @PreFilter("")//2.对集合类的参数或返回值进行过滤
    @PostFilter("")//2.对集合类的参数或返回值进行过滤
    @RequestMapping("/roleAuth")
    public String role(){
        return "admin  Auth";
    }
    

2.注解的参数该怎么传

or用法:
在这里插入图片描述
参数的值判断
在这里插入图片描述
and运算
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

混沌人生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值