广告
返回顶部
首页 > 资讯 > 后端开发 > Python >springSecurity实现简单的登录功能
  • 150
分享到

springSecurity实现简单的登录功能

2024-04-02 19:04:59 150人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

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

前言

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运算

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。

--结束END--

本文标题: springSecurity实现简单的登录功能

本文链接: https://www.lsjlt.com/news/166964.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • springSecurity实现简单的登录功能
    前言 1、不使用数据库,实现一个简单的登录功能,只有在登录后才能访问我们的接口2、springSecurity提供了一种基于内存的验证方法(使用自己定义的用户,不使用默认的) 一、实...
    99+
    2022-11-13
  • SpringSecurity OAuth2如何实现单点登录和登出功能
    这篇文章将为大家详细讲解有关SpringSecurity OAuth2如何实现单点登录和登出功能,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。1. 单点登录单点登录即有多个子系统,有一个认证中心...
    99+
    2023-06-29
  • Servlet简单实现登录功能
    本文实例为大家分享了Servlet简单实现登录功能的具体代码,供大家参考,具体内容如下 介绍: Servlet 是 JavaWeb 三大组件之一。三大组件分别是:Servlet 程序...
    99+
    2022-11-11
  • SpringSecurity 表单登录的实现
    目录表单登录登录成功登录失败注销登录自定义注销成功的返回内容表单登录 @Configuration public class SecurityConfig extends We...
    99+
    2022-11-12
  • spring MVC实现简单登录功能
    spring-MVC实现简单的登录功能,供大家参考,具体内容如下 今天我学习了spring-MVC实现简单的登录功能,本篇博客就讲解如何使用spring-MVC实现简单的登录功能 首...
    99+
    2022-11-13
  • vue+tp5实现简单登录功能
    本文实例为大家分享了vue+tp5实现简单登录功能的具体代码,供大家参考,具体内容如下 准备工作:安装vue-cli,element-ui,package.json中如图所示,看着安...
    99+
    2022-11-12
  • SpringSecurity使用单点登录的权限功能
    目录背景Spring Security实现已经有了单点登录页面,Spring Security怎么登录,不登录可以拿到权限吗Authentication继续分析结论如何手动登录Spr...
    99+
    2022-11-13
  • JavaWeb实现简单的自动登录功能
    本文实例为大家分享了JavaWeb实现简单的自动登录功能的具体代码,供大家参考,具体内容如下 用最近所学的知识点实现自动登录,主要有: 1、Filter过滤器 2、session &...
    99+
    2022-11-12
  • node.js实现简单登录注册功能
    本文实例为大家分享了node.js实现简单登录注册的具体代码,供大家参考,具体内容如下 1、首先需要一个sever模块用于引入路由,引入连接数据库的模块,监听服务器2、要有model...
    99+
    2022-11-13
  • SpringBoot+Vue实现简单的登录注册功能
    文章目录 一、前言1.开发环境2.功能3.项目运行截图 二、撸代码1.构建前端项目2.构建后端项目3.前端页面编写4.后端代码编写5.前后端联调 三、小结 一、前言 ...
    99+
    2023-09-20
    vue.js spring boot java mysql
  • Python+Tkinter简单实现注册登录功能
    本文实例为大家分享了Python+Tkinter简单实现注册登录功能的具体代码,供大家参考,具体内容如下 项目结构: 源代码: # -*- coding: utf-8 -*...
    99+
    2022-11-13
  • SpringSecurity整合springBoot、redis实现登录互踢功能
    背景 基于我的文章——《SpringSecurity整合springBoot、redis token动态url权限校验》。要实现的功能是要实现一个用户不可以同时在两台设备上登录,有两...
    99+
    2022-11-12
  • 简单实现小程序授权登录功能
           本人给大家带来了关于微信小程序的相关知识,其中主要介绍了怎么实现小程序授权登录功能的相关内容,下面一起来看一下,希望对大家有帮助。        在我们平时工作、学习、生活中,微信小程序已成为我们密不可分的一部分,我们仔细留意...
    99+
    2023-09-02
    小程序
  • node.js如何实现简单登录注册功能
    本文小编为大家详细介绍“node.js如何实现简单登录注册功能”,内容详细,步骤清晰,细节处理妥当,希望这篇“node.js如何实现简单登录注册功能”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。首先需要一个sev...
    99+
    2023-06-30
  • jsp+servlet实现简单登录页面功能(附demo)
    目录实现功能:开发环境:预备知识: 1.登录界面login.jsp:2.登录成功界面hello.jsp:3.登录失败信息回显Login.jsp:思路简述:具体代码Code:...
    99+
    2022-11-12
  • SpringSecurity整合springBoot、redis实现登录互踢功能的示例
    这篇文章主要介绍了SpringSecurity整合springBoot、redis实现登录互踢功能的示例,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。背景要实现的功能是要实现...
    99+
    2023-06-15
  • OpenCV实现简单录屏功能
    本文实例为大家分享了OpenCV实现简单录屏功能的具体代码,供大家参考,具体内容如下 OpenCV中VideoCapture和VideoWriter用于读写视频文件,这里的录屏功能用...
    99+
    2022-11-13
  • 怎么用php实现简单登录和注册功能
    要实现简单的登录和注册功能,可以按照以下步骤使用PHP编写代码:1. 创建数据库表格在数据库中创建一个名为 `users` 的表格,...
    99+
    2023-10-10
    php
  • 怎么用jsp+servlet实现简单登录页面功能
    本篇内容主要讲解“怎么用jsp+servlet实现简单登录页面功能”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么用jsp+servlet实现简单登录页面功能”吧!目录实现功能:开发环境:预备...
    99+
    2023-06-20
  • springsecurity集成cas实现单点登录过程
    目录cas流程下面代码解决的问题具体代码使用总结cas流程 如下 用户发送请求,后台服务器验证ticket(票据信息),未登录时,用户没有携带,所以验证失败,将用户重定向到cas服务...
    99+
    2023-02-16
    spring security spring security集成cas cas实现单点登录
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作